如何使用下面提供的params转换为UTC时间?
问题描述:
如果提供的日期为01st Jan, 2nd Jan
,它应该提供UTC
的输出以及当前年份和时间。如何使用下面提供的params转换为UTC时间?
Output : 2017-01-02T06:40:00Z
答
您不仅可以使用datetime
模块由于序号不处理。
但是你可以使用正则表达式来重新格式化您的输入,然后strptime
使用strftime
其转换为datetime
,你可以转换回字符串:
import re
import datetime
str_date = "2nd Jan"
now = datetime.datetime.utcnow()
PATTERN = re.compile(r"^0*(?P<day>[1-9]\d*)[^ ]* (?P<month>\w+)$")
reformatted = PATTERN.sub(r"\g<day> \g<month> %s", str_date) % now.strftime("%Y %H:%M:%S")
date = datetime.datetime.strptime(reformatted, "%d %b %Y %H:%M:%S")
print date.strftime("%Y-%m-%dT%H:%M:%SZ")
将输出:2017-01-02T09 :03:54Z
非常好,谢谢。你能否从最后一行的Z中删除%符号。 –