如何使用如下所示的参数转换为UTC时间?

时间:2017-10-06 07:57:30

标签: python-2.7 datetime utc

如果提供的日期与01st Jan, 2nd Jan一样,它应该在UTC中提供输出以及当前年份和时间。

Output : 2017-01-02T06:40:00Z

1 个答案:

答案 0 :(得分:1)

您不仅可以使用datetime模块,因为不会处理序数。

但您可以使用正则表达式重新格式化输入,然后strptime将其转换为datetime,您可以使用strftime转换回字符串:

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