问题描述
我有url以这种格式返回日期
I have url that returns date in this format
url_date = "2015-01-12T08:43:02Z"
我不知道为什么有字符串,将它变得更简单为2015-01-1208:43:02
使用
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')
但它不工作。我尝试过
%Y-%m-%d
%Y-%m-%d-%H-%M-%S
%Y-%m-%d-%H-%M-%S-%Z
但是我不断收到错误,如时间数据2015-01-12T08:43:02Z不匹配...
But I keep getting errors like "time data 2015-01-12T08:43:02Z does not match ..."
推荐答案
您正在寻找的格式是 - '%Y-%m-%dT%H:%M:%SZ'
。
The format you are looking for is - '%Y-%m-%dT%H:%M:%SZ'
.
示例 -
>>> 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 -
您需要使用 .strftime()
c $ c> datetime.datetime 对象,格式为 - '%Y-%m-%d:%H:%M:%S'
。示例 -
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'
如果您想要时间组件,可以使用 .time()
。示例 -
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)
这篇关于Python解析日期与strptime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!