Search code examples
pythonpandasdatetimestrptimestrftime

KeyValue error when trying to convert datetime.datetime object using strftime in Python


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?


Solution

  • 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].