Python日期时间如何在不同本地时区之间进行转换(+奖励DST)

3

我有些困惑,不太明白为什么会得到这样的结果。

我想尝试的是:

  1. Take two timezones, one that uses DST and one that doesn't. ex: Romania (dst) and Venezuela(no dst).

  2. For the timezone that has dst, create two datetimes. One in the interval of the dst, and one that isn't. Romania DST interval (4-10 / April-October). Ex:

    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) 
    
  3. Shouldn't x and y have different hours? Because date1 is in the DST interval, so 5 o'clock should mean a different hour than 5 o'clock in date2 when the datetime isn't in the DST interval.

然而,当转换为无夏令时时区时,xy都具有相同的小时数。

感谢您提供的任何解释。

1个回答

4

如果要使用pytz时区,就不能使用datetime构造函数,而需要使用localize函数:

date1 = tz1.localize(datetime(2016, 5, 5, 5, 0, 0))
date2 = tz1.localize(datetime(2016, 12, 5, 5, 0, 0))

来自文档

不幸的是,对于许多时区,使用标准datetime构造函数的tzinfo参数与pytz配合使用“无法正常工作”。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接