pfc
pfc

Reputation: 1910

Python format time string to datetime object

I'm trying to format the time string "2016-01-01 00:00:00" to a datetime object. I tried the following code:

from datetime import datetime
a = '2016-01-01 00:00:00'
d = datetime.strptime(a,'%Y%m%d %H:%M:%S')

But I got the error message saying:

ValueError: time data '2016-01-01 00:00:00' does not match format '%Y%m%d %H:%M:%S'

What's wrong with my code? Thank you all for helping me!!!

Upvotes: 2

Views: 2002

Answers (2)

Haroldo_OK
Haroldo_OK

Reputation: 7270

Your format string is wrong. This works:

from datetime import datetime
a = '2016-01-01 00:00:00'
d = datetime.strptime(a,'%Y-%m-%d %H:%M:%S')

Upvotes: 0

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48110

- hyphens are missing in your format string:

>>> from datetime import datetime
>>> a = '2016-01-01 00:00:00'

#                Hyphens here  v  v       
>>> d = datetime.strptime(a,'%Y-%m-%d %H:%M:%S')
>>> d
datetime.datetime(2016, 1, 1, 0, 0)

Upvotes: 6

Related Questions