Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i extract day of week from timestamp in pandas

I have a timestamp column in a dataframe as below, and I want to create another column called day of week from that. How can do it?

Input:

Pickup date/time    
07/05/2018 09:28:00                     
14/05/2018 17:00:00                      
15/05/2018 17:00:00                      
15/05/2018 17:00:00                     
23/06/2018 17:00:00                     
29/06/2018 17:00:00  

Expected Output:

Pickup date/time      Day of Week
07/05/2018 09:28:00     Monday                
14/05/2018 17:00:00     Monday                  
15/05/2018 17:00:00     Tuesday                 
15/05/2018 17:00:00     Tuesday               
23/06/2018 17:00:00     Saturday              
29/06/2018 17:00:00     Friday
like image 679
Rahul rajan Avatar asked Jul 30 '18 02:07

Rahul rajan


People also ask

How do you get the day of the week in pandas?

The dayofweek property is used to get the day of the week. The day of the week with Monday=0, Sunday=6. Note: It is assumed the week starts on Monday, which is denoted by 0 and ends on Sunday which is denoted by 6. This method is available on both Series with datetime values (using the dt accessor) or DatetimeIndex.

How do I convert datetime to days in Python?

Python datetime. date(year, month, day) :MINYEAR <= year <= MAXYEAR. 1 <= month <= 12. 1 <= day <= number of days in the given month and year.


1 Answers

You can use weekday_name

df['date/time'] = pd.to_datetime(df['date/time'], format = '%d/%m/%Y %H:%M:%S')

df['Day of Week'] = df['date/time'].dt.weekday_name

You get

    date/time   Day of Week
0   2018-05-07 09:28:00 Monday
1   2018-05-14 17:00:00 Monday
2   2018-05-15 17:00:00 Tuesday
3   2018-05-15 17:00:00 Tuesday
4   2018-06-23 17:00:00 Saturday
5   2018-06-29 17:00:00 Friday

Edit:

For the newer versions of Pandas, use day_name(),

df['Day of Week'] = df['date/time'].dt.day_name()
like image 112
Vaishali Avatar answered Oct 21 '22 13:10

Vaishali