日期时间:获取带有时区偏移量的时间戳 [英] datetime: get timestamp with timezone offset
问题描述
我想从以下格式的日期中获取时间戳:
I would like to get the timestamp from dates in the following formats:
Mon, 23 Nov 2020 19:00:00 GMT
Mon, 23 Nov 2020 20:00:00 +0100
我使用以下语句将日期转换为 datetime
对象:
I am using the the following statements to convert dates to datetime
objects:
dateobj = datetime.datetime.strptime(date, '%a, %d %b %Y %H:%M:%S %Z')
dateobj = datetime.datetime.strptime(date, '%a, %d %b %Y %H:%M:%S %z')
但是使用 .timestamp()
方法,会打印与纪元不同的秒数.为什么 %Z
指令不向 datetime
对象添加时区信息?如何将时区考虑在内,使时间戳相等?
But using .timestamp()
method, different seconds from epoch are printed. Why doesn't the %Z
directive add timezone information to the datetime
object? How could I get the timezone into account, so the timestamp is equal?
推荐答案
请注意 Python 中日期时间解析时区不一致.您的问题是 %Z
,它使 strptime
接受 某些字符串(GMT、UTC 和 time.tzname 中的任何值 - docs),但实际上并没有从中做出任何贡献.返回的日期时间对象是幼稚的——这就是为什么如果你调用它的 timestamp()
方法,Python 会假设它是本地时间.
Please note Inconsistent datetime parse timezone in Python. Your problem is %Z
, it makes strptime
accept certain strings (GMT, UTC and any value in time.tzname - docs), but doesn't actually make anything out of it. The returned datetime object is naive - which is why Python will assume it's local time if you call the timestamp()
method of it.
您可以改用 dateutil 的解析器:
You can use dateutil's parser instead:
from dateutil.parser import parse
for s in ("Mon, 23 Nov 2020 19:00:00 GMT", "Mon, 23 Nov 2020 20:00:00 +0100"):
dt = parse(s)
print(repr(dt), dt.timestamp())
# datetime.datetime(2020, 11, 23, 19, 0, tzinfo=tzutc()) 1606158000.0
# datetime.datetime(2020, 11, 23, 20, 0, tzinfo=tzoffset(None, 3600)) 1606158000.0
这篇关于日期时间:获取带有时区偏移量的时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!