2

I'm quite new in the Python world and I need to extract the exact weekdays from a long column of specific dates in my dataset. The column looks like this:

0       1/5/2019
1       3/8/2019
2       3/3/2019
3      1/27/2019
4       2/8/2019
         ...    
995    1/29/2019
996     3/2/2019
997     2/9/2019
998    2/22/2019
999    2/18/2019
Name: Date, Length: 1000, dtype: object

I've been trying with the packages datetime and calendar as well as coding with for loop, but I can't figure out how to get Python to read the entire column and let me extract the weekdays in a new column. Thank you in advance!!

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
somo
  • 21
  • 1

1 Answers1

2

It looks like your data is in a pandas Series, which has date functionality built in.

First you have to convert the string values to date objects, and then you can use the date functionality through .dt to get the weekday:

import pandas as pd
timeseries = pd.Series(["1/27/2015", "5/4/2012"])
pd.to_datetime(timeseries).dt.weekday  # --> [1, 4]
pd.to_datetime(timeseries).dt.day_name()  # --> ["Tuesday", "Friday"]

Pitfall: the default for pd.to_datetime is month/day/year. If your data is in day/month/year format and you don't specify the format, pandas will parse whatever rows it can as m/d/y and the remaining rows as d/m/y, silently messing up some of the dates.

Swier
  • 4,047
  • 3
  • 28
  • 52