Python(日期时间)时区转换关闭 4 分钟

标签 python datetime timezone utc

当我运行此代码时:

#!/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”

最佳答案

From pytz documentation :

This library differs from the documented Python API for tzinfo implementations; if you want to create local wallclock times you need to use the localize() method documented in this document. In addition, if you perform date arithmetic on local times that cross DST boundaries, the result may be in an incorrect timezone (ie. subtract 1 minute from 2002-10-27 1:00 EST and you get 2002-10-27 0:59 EST instead of the correct 2002-10-27 1:59 EDT).



因此,您错误地使用了 pytz。

以下是正确和错误的代码 以下代码显示了您使用 pytz ( datetime.replace(tzinfo=pytz.timezone) ) 的结果,以及使用 pytz 和 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 时间不随时区变化。
t6已使用 pytz.timezone.localize() 创建方法,并给出正确的 UTC 偏移量 (-5:00)。

更新 :将答案的语言更新为 one user found the answer confusing .

关于Python(日期时间)时区转换关闭 4 分钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60996205/

相关文章:

java - SimpleDateFormat 给出不一致的结果

timezone - Azure Web应用服务时区更改问题

python - 类似 python 的 puppet 语法

python - 操作系统在文件上循环打印两次

MySQL DATETIME DIFF 查询

python - SQL Where 子句和 Django 时区

python - 从数据库读取数据后出现问题 ValueError : invalid literal for int() with base 10: '\r'

python - 如何在 Flask 中创建服务?

mysql - 在 MySQL SELECT 语句中插入空白行

Python 3 - pd.to_datetime 无法识别时区