I was working on a pandas dataframe where I had a column of datetime now I haveto convert it into Weekdays.How can I do this?
There is a datetime module you may want to use.
strptime and strftime methods from datetime module:
In [1]: import datetime
In [4]: datetime.datetime.strptime('01-01-2011 19:00','%d-%m-%Y %H:%M').strftime('%A')
Out[4]: 'Saturday'
You can use datetime.strftime()
to parse the date then use datetime.weekday()
to get the weekday as an integer:
Example:
from datetime import datetime
d = datetime.strptime("01-01-2011 19:00", "%d-%m-%Y %H:%S")
d.weekday() # 5
Now if we look at the documentation for datetime.weekday()
we can see:
date.weekday()
Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
For example, date(2002, 12, 4).weekday() == 2, a Wednesday.
See also isoweekday().
So knowing this we can write a simple function:
weekdays = {
0: "Monday",
1: "Tuesday",
2: "Wednesday",
3: "Thursday",
4: "Friday",
5: "Saturday",
6: "Sunday",
}
def weekday(dt):
return weekdays[dt.weekday()]
Now we can simply call weekday()
on a given datetime()
object instance:
d = datetime.strftime(">>> d = datetime.strptime("01-01-2011 19:00", "%d-%m-%Y %H:%S")
weekday(d) # Saturday
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With