Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 256
Shilpi Agrawal Avatar asked Feb 11 '23 01:02

Shilpi Agrawal


2 Answers

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'
like image 65
Ajay Avatar answered Feb 15 '23 10:02

Ajay


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
like image 22
James Mills Avatar answered Feb 15 '23 11:02

James Mills