Python parsing date with strptime

◇◆丶佛笑我妖孽 提交于 2019-12-02 00:48:41

问题


I have url that returns date in this format

url_date = "2015-01-12T08:43:02Z"

I don't know why there are strings, it would have been simpler to get it as "2015-01-1208:43:02" which would have been simpler to parse using

datetime.datetime.strptime(url_date , '%Y-%m-%d')

but it does not work. I have tried with

%Y-%m-%d
%Y-%m-%d-%H-%M-%S
%Y-%m-%d-%H-%M-%S-%Z

But I keep getting errors like "time data 2015-01-12T08:43:02Z does not match ..."


回答1:


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)



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


来源:https://stackoverflow.com/questions/33397107/python-parsing-date-with-strptime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!