简体   繁体   中英

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!!!

- 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)

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM