问题描述
当我运行此代码时:
#!/usr/bin/env python3
from datetime import datetime, timedelta
from dateutil import tz
from pytz import timezone
time = "2020-01-15 10:14:00"
time = datetime.strptime(time, "%Y-%m-%d %H:%M:%S")
print("time1 = " + str(time))
time = time.replace(tzinfo=timezone('America/New_York'))
print("time2 = " + str(time))
time = time.astimezone(tz.gettz('UTC')) # explicity convert to UTC time
print("time3 = " + str(time))
time = datetime.strftime(time, "%Y-%m-%d %H:%M:%S") # output format
print("done time4 = " + str(time))
我得到这个输出:
time1 = 2020-01-15 10:14:00
time2 = 2020-01-15 10:14:00-04:56
time3 = 2020-01-15 15:10:00+00:00
done time4 = 2020-01-15 15:10:00
我原以为最后一次是2020-01-15 15:14:00",有人知道为什么它比 4 分钟晚吗?我不明白为什么 time2 中的偏移量会是-04:56"而不是-05:00"
I would have expected the final time to be "2020-01-15 15:14:00" anyone have any ideas why it's off by 4 mintutes? I don't understand why the offset in time2 would by "-04:56" instead of "-05:00"
推荐答案
这个库不同于记录在案的用于 tzinfo 实现的 Python API;如果您想创建本地挂钟时间,您需要使用本文档中记录的 localize()
方法.此外,如果您对跨越 DST 边界的本地时间执行日期算术,则结果可能位于不正确的时区(即从 2002-10-27 1:00 EST 减去 1 分钟,您会得到 2002-10-27 0:59 EST 而不是正确的 2002-10-27 1:59 EDT).
所以,您错误地使用了 pytz.
So, you are using pytz incorrectly.
以下代码显示了您使用 pytz (datetime.replace(tzinfo=pytz.timezone)
) 的结果,以及推荐的使用带有日期时间的 pytz 的方式 (pytz.timezone.localize(datetime)
).
Following code shows results of your use of pytz (datetime.replace(tzinfo=pytz.timezone)
), and the recommended way of using pytz with datetime (pytz.timezone.localize(datetime)
).
from datetime import datetime, date, time, timezone
from dateutil import tz
import pytz
d = date(2019, 1, 27)
t = time(19, 32, 00)
t1 = datetime.combine(d, t)
t1_epoch = t1.timestamp()
print("t1_epoch " + str(t1_epoch))
print("t1 " + str(t1))
# your approach/code
nytz = pytz.timezone('America/New_York')
t3 = t1.replace(tzinfo=nytz)
t3_epoch = t3.timestamp()
print("t3_epoch " + str(t3_epoch))
print("t3 " + str(t3))
# recommended approach/code using localize
nytz = pytz.timezone('America/New_York')
t6 = nytz.localize(t1)
t6_epoch = t6.timestamp()
print("t6_epoch " + str(t6_epoch))
print("t6 " + str(t6))
以上代码的输出:
t1_epoch 1548617520.0
t1 2019-01-27 19:32:00
t3_epoch 1548635280.0
t3 2019-01-27 19:32:00-04:56
t6_epoch 1548635520.0
t6 2019-01-27 19:32:00-05:00
t3
就是你在做什么,它给出了不正确的偏移量(-4:56).请注意,在这种情况下,POSIX 时间也不正确.根据定义,POSIX 时间不随时区变化.
t3
is what you are doing, and it is giving incorrect offset (-4:56). Note that POSIX time is also incorrect in this case. POSIX time, by definition, does not change with timezone.
t6
已使用 pytz.timezone.localize()
方法创建,并提供正确的 UTC 偏移量 (-5:00).
t6
has been created using pytz.timezone.localize()
method, and gives correct UTC offset (-5:00).
更新:将答案的语言更新为 一位用户发现答案令人困惑.
Update: Updated language of the answer as one user found the answer confusing.
这篇关于Python(日期时间)时区转换关闭 4 分钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!