Python parsing date with strptime

♀尐吖头ヾ 提交于 2019-12-01 22:06:50

The format you are looking for is - '%Y-%m-%dT%H:%M:%SZ' .

Example -

>>> url_date = "2015-01-12T08:43:02Z"
>>> import datetime
>>> datetime.datetime.strptime(url_date , '%Y-%m-%dT%H:%M:%SZ')
datetime.datetime(2015, 1, 12, 8, 43, 2)

For the new requirement in comments -

if I wanted to get a time back with the strings as in 2015-01-12:08:43:02 which methods should after datetime().datetime()

You would need to use .strftime() on the datetime.datetime object with the format - '%Y-%m-%d:%H:%M:%S'. Example -

>>> url_date = "2015-01-12T08:43:02Z"
>>> dt = datetime.datetime.strptime(url_date , '%Y-%m-%dT%H:%M:%SZ')
>>> dt.strftime('%Y-%m-%d:%H:%M:%S')
'2015-01-12:08:43:02'

If you wanted the time component , you can use .time() for that. Example -

>>> dt = datetime.datetime.strptime(url_date , '%Y-%m-%dT%H:%M:%SZ')
>>> dt.time()
datetime.time(8, 43, 2)

You were getting close with the "Z" in your final attempt - you need to specify the T, Z, and colon literal values in your format string.

>>> import datetime
>>> url_date = "2015-01-12T08:43:02Z"
>>> datetime.datetime.strptime(url_date , '%Y-%m-%dT%H:%M:%SZ')
datetime.datetime(2015, 1, 12, 8, 43, 2)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!