Python 从一个本地时区到另一个本地时区的日期时间转换(+ 奖励 DST)
Python datetime conversions from one local timezone to another (+ bonus DST's)
我无法理解为什么我会得到我得到的结果。
我想尝试的:
取两个时区,一个使用夏令时,一个不使用。例如:罗马尼亚(夏令时)和委内瑞拉(无夏令时)。
对于具有夏令时的时区,创建两个日期时间。一个在 dst 的间隔内,一个不在 dst 的间隔内。罗马尼亚夏令时间隔(4 月至 10 日/4 月至 10 月)。例如:
from datetime import datetime
from pytz import timezone
tz1 = timezone('Europe/Bucharest')
tz2 = timezone('America/Caracas')
date1 = datetime(2016, 5, 5, 5, 0, 0, tzinfo=tz1) # its in the dst interval (5 o'clock, summer - dst)
date1 = datetime(2016, 12, 5, 5, 0, 0, tzinfo=tz1) # isn't in the dst interval (5 o'clock, winter - no dst)
x = date1.astimezone(tz2)
y = date2.astimezone(tz2)
x
和 y
不应该有不同的时间吗?因为 date1 在 DST 间隔内,所以当日期时间不在 DST 间隔内时,5 点钟应该与 date2 中的 5 点钟表示不同的小时。
然而,x
和 y
在转换为无 DST 时区时具有相同的小时。
感谢您的解释。
您不能使用 datetime
构造函数来使用 pytz
时区,您必须使用 localize
:
date1 = tz1.localize(datetime(2016, 5, 5, 5, 0, 0))
date2 = tz1.localize(datetime(2016, 12, 5, 5, 0, 0))
Unfortunately using the tzinfo argument of the standard datetime constructors ‘‘does not work’’ with pytz for many timezones.
我无法理解为什么我会得到我得到的结果。
我想尝试的:
取两个时区,一个使用夏令时,一个不使用。例如:罗马尼亚(夏令时)和委内瑞拉(无夏令时)。
对于具有夏令时的时区,创建两个日期时间。一个在 dst 的间隔内,一个不在 dst 的间隔内。罗马尼亚夏令时间隔(4 月至 10 日/4 月至 10 月)。例如:
from datetime import datetime from pytz import timezone tz1 = timezone('Europe/Bucharest') tz2 = timezone('America/Caracas') date1 = datetime(2016, 5, 5, 5, 0, 0, tzinfo=tz1) # its in the dst interval (5 o'clock, summer - dst) date1 = datetime(2016, 12, 5, 5, 0, 0, tzinfo=tz1) # isn't in the dst interval (5 o'clock, winter - no dst) x = date1.astimezone(tz2) y = date2.astimezone(tz2)
x
和y
不应该有不同的时间吗?因为 date1 在 DST 间隔内,所以当日期时间不在 DST 间隔内时,5 点钟应该与 date2 中的 5 点钟表示不同的小时。
然而,x
和 y
在转换为无 DST 时区时具有相同的小时。
感谢您的解释。
您不能使用 datetime
构造函数来使用 pytz
时区,您必须使用 localize
:
date1 = tz1.localize(datetime(2016, 5, 5, 5, 0, 0))
date2 = tz1.localize(datetime(2016, 12, 5, 5, 0, 0))
Unfortunately using the tzinfo argument of the standard datetime constructors ‘‘does not work’’ with pytz for many timezones.