Skip to content
Advertisement

Set the format for pd.to_datetime

Hi already referred to this post but I could not get through my issue. I have a column in my CSV which is string and the sample values are below (note that the month and year positioning are sometimes reversed). What format do I need to set in my to_datetime? I tried all the below approaches

JavaScript

I get the error

ValueError: day is out of range for month

for [1] and I get

ValueError: time data ‘Mar-97’ does not match format ‘%m/%d/%Y’ (match)

for [2]. I tried to remove the %d too but no luck. Could you please point me what is going wrong here.

Advertisement

Answer

One way is to use try / except with pd.Series.apply:

JavaScript

Since we have defined converter as a function, we can use this directly with pd.read_csv:

JavaScript

Python’s strftime directives is a useful reference for constructing datetime format strings.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement