【问题标题】:pytz: _utcoffset has a wrong value for Iranpytz:_utcoffset 对伊朗的值错误
【发布时间】:2013-08-17 18:43:50
【问题描述】:

正确值:

>>> pytz.timezone('Asia/Tehran').utcoffset(datetime(2013, 1, 1)).total_seconds()/3600.0
3.5

>>> pytz.timezone('Asia/Tehran').utcoffset(datetime(2013, 1, 1)).total_seconds()
12600.0

值不正确:

>>> pytz.timezone('Asia/Tehran')._utcoffset.total_seconds()/3600.0
3.433333333333333

>>> pytz.timezone('Asia/Tehran')._utcoffset.total_seconds()
12360.0

我想知道utcoffset()方法中是否使用了_utcoffset属性,为什么该方法在属性错误时起作用。
无论如何看起来像一个错误。
如果将 Asia/Tehran 替换为 Iran,则没有任何变化

>>> print pytz.VERSION
2012c

操作系统:Linux Mint 15 (Olivia)
使用 Python 2.7

【问题讨论】:

    标签: python timezone utc pytz


    【解决方案1】:

    让我们看看这里发生了什么:

    >>> tz = pytz.timezone('Asia/Tehran')
    >>> tz
    <DstTzInfo 'Asia/Tehran' LMT+3:26:00 STD>
    

    这意味着时区以LMT 表示 - 这是太阳时。这就是为什么您会看到 utcoffset 为 12360 - 这里没有错误,它只是使用不同的参考计算得出的。

    现在如果你这样做:

    >>> d = tz.localize(datetime(2013, 1, 1))
    >>> d
    datetime.datetime(2013, 1, 1, 0, 0, tzinfo=<DstTzInfo 'Asia/Tehran' IRST+3:30:00 STD>)
    >>> d.utcoffset()
    datetime.timedelta(0, 12600)
    

    localize 方法导致表示切换到在该日期和地点使用的正确时区,即 IRST,utcoffset 为 12600 秒。

    这正是 tzinfo 对象的 utcoffset method 所做的 - 它本地化给定的日期时间对象并返回它的 utcoffset。

    如果你现在这样做了,也一样:

    >>> d = datetime.now(tz)
    >>> d
    datetime.datetime(2013, 8, 15, 20, 46, 4, 705896, tzinfo=<DstTzInfo 'Asia/Tehran' IRDT+4:30:00 DST>)
    >>> d.utcoffset()
    datetime.timedelta(0, 16200)
    

    您将获得以 IRDT 表示的日期时间,因为当前夏令时在该时区有效。

    【讨论】:

    • 为什么pytz默认是LMT?似乎不太可能有人会期望或希望看到默认情况下的 LMT 抵消。 Pytz 应该采用合理的默认值并警告偏移量取决于特定日期,或者只是抛出一个错误。
    • @rinspy 该行为具有历史意义,有关一些信息,请参阅bugs.launchpad.net/pytz/+bug/1319939/comments/12。此外,_utcoffset 属性不是公共 api。
    猜你喜欢
    • 2011-10-25
    • 2018-08-26
    • 2018-07-21
    • 2016-10-29
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    • 2019-05-24
    • 2022-10-14
    相关资源
    最近更新 更多