Home > other >  "Bad directive" value error when converting to Pandas datetime
"Bad directive" value error when converting to Pandas datetime

Time:04-23

I have a Pandas dataframe df that looks as follows:

df = pd.DataFrame({'timestamp' : ['Wednesday, Apr 4/04/22 at 17:02',
                                  'Saturday, Apr 4/23/22 at 15:45'],
                        'foo' : [1, 2]
                       })

df
    timestamp                          foo
0   Wednesday, Apr 4/04/22 at 17:02    1
1   Saturday, Apr 4/23/22 at 15:45     2

I'm trying to convert the timestamp column to a datetime object so that I can add a day_of_week column.

My attempt:

df['timestamp'] = pd.to_datetime(df['timestamp'],
                                 format='%A, %b %-m/%-d/%y at %H:%M')
df['day_of_week'] = df['timestamp'].dt.day_name()

The error is:

ValueError: '-' is a bad directive in format '%A, %b %-m/%-d/%y at %H:%M'

Any assistance would be greatly appreciated. Thanks!

CodePudding user response:

Just use the format without the -:

df['timestamp'] = pd.to_datetime(df['timestamp'],
                                 format='%A, %b %m/%d/%y at %H:%M')
df['day_of_week'] = df['timestamp'].dt.day_name()

NB. to_datetime is quite flexible on the provided data, note how the incorrect day of week was just ignored.

output:

            timestamp  foo day_of_week
0 2022-04-04 17:02:00  1    Monday    
1 2022-04-23 15:45:00  2    Saturday  
  • Related