Convert Date String to Day of Week
Question:
I have date strings like this:
'January 11, 2010'
and I need a function that returns the day of the week, like
'mon', or 'monday'
etc.
I can’t find this anywhere in the Python help.
Anyone? Thanks.
Answers:
>>> import time
>>> dateStr = 'January 11, 2010'
>>> timestamp = time.strptime(dateStr, '%B %d, %Y')
>>> timestamp
time.struct_time(tm_year=2010, tm_mon=1, tm_mday=11, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=11, tm_isdst=-1)
A third-party parser could be used, such as dateutil.
And code for your original question:
>>> from dateutil import parser
>>> parser.parse('January 11, 2010').strftime("%a")
'Mon'
>>> parser.parse('January 11, 2010').strftime("%A")
'Monday'
use date.weekday()
Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
http://docs.python.org/2/library/datetime.html#datetime.date.weekday
You might want to use strptime and strftime
methods from datetime
:
>>> import datetime
>>> datetime.datetime.strptime('January 11, 2010', '%B %d, %Y').strftime('%A')
'Monday'
or for 'Mon'
:
>>> datetime.datetime.strptime('January 11, 2010', '%B %d, %Y').strftime('%a')
'Mon'
import time
time.strftime('%A')
I think the fastest way to do it like below:
df[Date_Column].dt.weekday_name
I have date strings like this:
'January 11, 2010'
and I need a function that returns the day of the week, like
'mon', or 'monday'
etc.
I can’t find this anywhere in the Python help.
Anyone? Thanks.
>>> import time
>>> dateStr = 'January 11, 2010'
>>> timestamp = time.strptime(dateStr, '%B %d, %Y')
>>> timestamp
time.struct_time(tm_year=2010, tm_mon=1, tm_mday=11, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=11, tm_isdst=-1)
A third-party parser could be used, such as dateutil.
And code for your original question:
>>> from dateutil import parser
>>> parser.parse('January 11, 2010').strftime("%a")
'Mon'
>>> parser.parse('January 11, 2010').strftime("%A")
'Monday'
use date.weekday()
Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
http://docs.python.org/2/library/datetime.html#datetime.date.weekday
You might want to use strptime and strftime
methods from datetime
:
>>> import datetime
>>> datetime.datetime.strptime('January 11, 2010', '%B %d, %Y').strftime('%A')
'Monday'
or for 'Mon'
:
>>> datetime.datetime.strptime('January 11, 2010', '%B %d, %Y').strftime('%a')
'Mon'
import time
time.strftime('%A')
I think the fastest way to do it like below:
df[Date_Column].dt.weekday_name