Ruffy26
Ruffy26

Reputation: 109

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!

Upvotes: 0

Views: 1228

Answers (3)

jezrael
jezrael

Reputation: 862661

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

Upvotes: 1

PyNico
PyNico

Reputation: 695

Duplicated question

Use datetime.strptime

Ex:

from datetime import datetime

date_object = datetime.strptime('2016Oct03:14:38:33', '%Y%b%d:%H:%M:%S')

Doc : https://docs.python.org/2/library/datetime.html

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599610

There doesn't seem to be anything unusual about the time format at all; 24 hour is absolutely standard.

Just the normal strptime is fine:

datetime.strptime(my_date, '%Y%b%d:%H:%M:%S')

Upvotes: 4

Related Questions