Ruffy26 Ruffy26 - 1 month ago 10
Python Question

How to convert unusual 24 hour date time format in python?

I have a dataframe column full datetime type that are in the format

2016Oct03:14:38:33


Right now, the data type of this column of the dataframe is String. I would like to convert it into datetime in order to be able perform some numerical operations like subtractions on them. I have tried specifying the format while using pd.to_datetime but as the time is in a 24 hr format, it is throwing up an error. What is the best way to do this? Thanks in advance!

Answer

You need to_datetime with parameter format:

df = pd.DataFrame({'dates':['2016Oct03:14:38:33',
                            '2016Oct03:14:38:33',
                            '2016Oct03:14:38:33']})

print (df)
                dates
0  2016Oct03:14:38:33
1  2016Oct03:14:38:33
2  2016Oct03:14:38:33

df.dates = pd.to_datetime(df.dates, format='%Y%b%d:%H:%M:%S')
print (df)
                dates
0 2016-10-03 14:38:33
1 2016-10-03 14:38:33
2 2016-10-03 14:38:33
Comments