How can we convert 01-01-2011 19:00 on weekdays like Mon, Tue .. in python?

I was working on a pandas file framework where I had a datetime column, now I haveto convert it to Weekdays. How can i do this?

+3


source to share


2 answers


There is a datetime module that you can use.

strptime and strftime 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'

      

+5


source


You can use datetime.strftime()

to parse a date and then use datetime.weekday()

to get the day of the week 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()

Returns the day of the week as an integer, where Monday is 0 and Sunday is 6.

For example date (2002, 12, 4) .weekday () == 2, 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 object instance datetime()

:

d = datetime.strftime(">>> d = datetime.strptime("01-01-2011 19:00", "%d-%m-%Y %H:%S")
weekday(d)  # Saturday

      

+2


source







All Articles