1

I'm attempting to convert values within a series from one datetime object format to another.

I've used the following to convert the original entry into a datetime object:

import datetime as dt
for each in DataFrame_name['Series_name']:
    DataFrame_name['Series_name'][each] = dt.datetime.strptime(each,"%Y-%m-%d %H:%M")

This has been effective at converting string entries such as '2019-07-01 12:14' into datetime objects.

However, when I attempt to convert this datetime format to '%Y-%m', I get the a KeyError: datetime.datetime(2019, 7, 1, 12, 14)

for each in DataFrame_name['Series_name']:
    DataFrame_name['Series_name'][each].strftime('%Y-%m')
KeyError: datetime.datetime(2018, 2, 1, 0, 0)

Has anyone seen/solved this before?

stovfl
  • 14,998
  • 7
  • 24
  • 51
Sam Waters
  • 13
  • 2

1 Answers1

0

Take another, more pandasonic approach.

Assume that the source DataFrame is:

                Dat  Score
0  2019-07-01 12:14    120
1  2019-07-02 10:20    130
2  2019-08-07 18:33    610

where Dat column is kept as a String and Score as int64 (as it could be read from an Excel or CSV file).

To convert Dat column from String to datetime, instead of importing datetime and your loop, just execute a single statement:

df.Dat = pd.to_datetime(df.Dat)

When you print(df), you will get:

                  Dat  Score
0 2019-07-01 12:14:00    120
1 2019-07-02 10:20:00    130
2 2019-08-07 18:33:00    610

The type of Dat is now datetime64[ns] and the format it is printed is as it is for datetime type.

Then, instead of reformatting it to text, convert it to Period with Month frequency, again with a single instruction:

df.Dat = df.Dat.dt.to_period('M')

The result is:

       Dat  Score
0  2019-07    120
1  2019-07    130
2  2019-08    610

and the type of Data is period[M].

Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41
  • Amazing thank you! That worked perfectly. I originally managed to find a solution using a for loop, but your method is much faster/simpler – Sam Waters Sep 20 '19 at 15:27