Convert Year/Month/Day to Day of Year in Python
Use datetime.timetuple()
to convert your datetime
object to a time.struct_time
object then get its tm_yday
property:
from datetime import datetime
day_of_year = datetime.now().timetuple().tm_yday # returns 1 for January 1st
Convert datetime to MonthName DAY,YEAR
How about this:
select
CONVERT(VARCHAR(12), dt, 107) AS [Mon DD, YYYY]
from temp
Output:
Jan 16, 2013
Live Demo
Convert date format to 'Month-Day-Year'
You could use pandas.Series.dt.strftime
(documentation) to change the format of your dates. In the code below I have a column with your old format dates, I create a new columns with this method:
import pandas as pd
df = pd.DataFrame({'old format': pd.date_range(start = '2020-01-01', end = '2020-06-30', freq = 'd')})
df['new format'] = df['old format'].dt.strftime('%m-%d-%Y')
Output:
old format new format
0 2020-01-01 01-01-2020
1 2020-01-02 01-02-2020
2 2020-01-03 01-03-2020
3 2020-01-04 01-04-2020
4 2020-01-05 01-05-2020
5 2020-01-06 01-06-2020
6 2020-01-07 01-07-2020
7 2020-01-08 01-08-2020
8 2020-01-09 01-09-2020
9 2020-01-10 01-10-2020
Transforming Datetime into month, day and year?
I don't know for
June 14th, 2010
But if you want
June 14, 2010
Ref how do i get name of the month in ruby on Rails? or this
Just do
@date = Time.now
@date.strftime("%B %d, %Y")
And for suffix use following
@date.strftime("%B #{@date.day.ordinalize}, %Y") # >>> Gives `June 18th, 2010`
How to convert year-month-day to just years in python?
Using just base Python (as you didn't specify that you have a pandas dataframe - pandas has specific functions to perform calculations with datetime objects):
from datetime import datetime
#takes as arguments the date as a string and an optional format string
def floatyear(str, fmtstr="%Y-%m-%d"):
t = datetime.strptime(str, fmtstr)
t_first = datetime(t.year, 1, 1, 0, 0, 0)
t_last = datetime(t.year, 12, 31, 0, 0, 0)
return t.year + ((t-t_first).days/(t_last-t_first).days)
print(floatyear("2018-10-24", "%Y-%m-%d"))
Sample output:
2018.8131868131868
Converting a date 'year - month - date' to only 'year and month' in r with SQL data
Up front, your attempt of as.Date(df$Posting_Date, format="%Y %m")
seems backwards: the function as.Date
is for converting from a string to a Date
-class, and its format=
argument is to identify how to find the year/month/day components of the string, not how you want to convert it later. (Note that in R, a Date
is shown as YYYY-MM-DD
. Always. Telling R you want a date to be just year/month is saying that you want to convert it to a string, no longer date-like or number-like. lubridate
and perhaps other packages allow you to have similar-to-Date
like objects.)
For df
, one can just subset the strings without parsing to Date
-class:
substring(df$Posting_Date, 1, 7)
# [1] "2020-05" "2020-10" "2021-10"
If you want to do anything number-like to them, you can convert to Date
-class first, and then use format(.)
to convert to a string with a specific format.
as.Date(df$Posting_Date)
# [1] "2020-05-28" "2020-10-09" "2021-10-19"
format(as.Date(df$Posting_Date), format = "%Y-%m")
# [1] "2020-05" "2020-10" "2021-10"
For df2
, though, since it is numeric you need to specify an origin=
instead of a format=
. I'm inferring that these are based off of epoch, so
as.Date(df2$Posting_Date, origin = "1970-01-01")
# [1] "2020-05-28" "2020-10-09" "2021-10-19"
format(as.Date(df2$Posting_Date, origin = "1970-01-01"), format = "%Y-%m")
# [1] "2020-05" "2020-10" "2021-10"
Note that R stores Date
(and POSIXct
, incidentally) as numbers internally:
dput(as.Date(df2$Posting_Date, origin = "1970-01-01"))
# structure(c(18410, 18544, 18919), class = "Date")
Convert date (month, day, year, time) to Datetime format in python
If you insist on comparing as strings...
from datetime import datetime
a = "2016-04-15T04:08:03.000+0000"
b = "Apr 15, 2016, 4:08:03 AM"
a = datetime.strptime(a, '%Y-%m-%dT%H:%M:%S.%f%z')
b = datetime.strptime(b, '%b %d, %Y, %I:%M:%S %p')
b = b.replace(tzinfo=a.tzinfo)
print(a.isoformat())
print(b.isoformat())
Extracting just Month and Year separately from Pandas Datetime column
If you want new columns showing year and month separately you can do this:
df['year'] = pd.DatetimeIndex(df['ArrivalDate']).year
df['month'] = pd.DatetimeIndex(df['ArrivalDate']).month
or...
df['year'] = df['ArrivalDate'].dt.year
df['month'] = df['ArrivalDate'].dt.month
Then you can combine them or work with them just as they are.
Related Topics
When to Use Curly Braces VS Parenthesis in Expect Rspec Method
How to Display a PDF in Ror (Ruby)
Uninitialized Constant Rake::Dsl in Ruby Gem
Rails: Validation in Model VS Migration
Active Admin - Refresh Second Drop Down Based on First Drop Down, Ruby on Rails
Maintaining Cookies Between Mechanize Requests
Shorten Long Numbers to Include K/M/B/T
Execute Ruby Code in Sublime Text 2
Rails 3.1 with Postgresql: Group by Must Be Used in an Aggregate Function
Private Class (Not Class Method) in a Ruby Module
How to Call an Older Version of a Gem from the Commandline
Iterating Between Two Datetimes, with a One Hour Step
How to Share Variables Across My .Rb Files
How to Remove Ruby from Ubuntu
Jekyll - Generating JSON Files Alongside the HTML Files