如何使用如下提供的参数转换为 UTC 时间?
How to convert into UTC time with params provided as below?
如果日期按 01st Jan, 2nd Jan
提供,它应该会在 UTC
中提供输出以及当前年份和时间。
Output : 2017-01-02T06:40:00Z
您不能只使用 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
如果日期按 01st Jan, 2nd Jan
提供,它应该会在 UTC
中提供输出以及当前年份和时间。
Output : 2017-01-02T06:40:00Z
您不能只使用 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