Home > Net >  Changing the format of a column of data in a Pandas Series
Changing the format of a column of data in a Pandas Series

Time:11-30

I would like to change the format of the returned dates from this:

listOfDates = df2['TradeDate'].drop_duplicates().reset_index(drop=True)
print(listOfDates)

0   2022-02-02
1   2022-02-08
2   2022-05-01
3   2022-05-06
4   2022-06-05
5   2022-06-17
6   2022-07-30
7   2022-08-03
8   2022-10-10
9   2022-11-18
Name: TradeDate, dtype: datetime64[ns]

to this:

listOfDates = df2['TradeDate'].drop_duplicates().reset_index(drop=True)
print(listOfDates)

0   20220202
1   20220208
2   20220501
3   20220506
4   20220605
5   20220617
6   20220730
7   20220803
8   20221010
9   20221118
Name: TradeDate, dtype: datetime64[ns]

I attempted the below, but to no avail as a pandas series has no attribute 'strftime':

listOfDates = df2['TradeDate'].drop_duplicates().reset_index(drop=True).strftime("%Y%m%d")

Any suggestions greatly appreciated, thanks!

CodePudding user response:

You need to use the datetime accessor dt like this:

listOfDates = df2['TradeDate'].drop_duplicates().reset_index(drop=True).dt.strftime("%Y%m%d")

Documented here

  • Related