How to add weekdays with year and month in pandas

Solution 1:

If I understood your question correctly, you want to have a column that contains the date in the format of 2020-10-Thu or 2020-10-04? If that's the case, the code below should work for you (Just note that the First Format and Second Format columns end up being of type string, also note that the weekdays begin with 1 where sunday is labelled as 0).

from datetime import datetime
import pandas as pd

originalDates = pd.date_range(start="2020-02-02",end="2020-03-03")
firstFormat = pd.Series([datetime.strftime(x, '%Y-%m-%a') for x in originalDates])
secondFormat = pd.Series([datetime.strftime(x, '%Y-%m-%w') for x in originalDates])

frame = {'Original Dates': originalDates, 'First Format': firstFormat, 'Second Format': secondFormat}

df = pd.DataFrame(frame)

The df variable ends up looking like this:

Original Dates First Format Second Format
2020-02-03 2020-02-Mon 2020-02-1
2020-02-04 2020-02-Tue 2020-02-2
2020-02-05 2020-02-Wed 2020-02-3

I'm sure there's a better way to do this, but I'm not aware of it at this time.