【问题标题】:python right-hand vs left-hand time stamps and DSTpython右手与左手时间戳和DST
【发布时间】:2015-08-22 15:43:14
【问题描述】:

我想知道 python 是否区分左手(左旋)和右手(右旋)时间戳。在 DST 天本地化时间戳时,这会成为一个问题。

假设我在欧洲当地时间的右侧标记了半小时值,在 2014 年 3 月 30 日从 02:00 小时到 03:00 小时发生了 DST 更改。

2014-03-30 00:30:00
2014-03-30 01:00:00
2014-03-30 01:30:00
2014-03-30 02:00:00
2014-03-30 03:30:00
2014-03-30 04:00:00

如果要本地化这些时间戳,自然会报错:

NonExistentTimeError: 2014-03-30 02:00:00

因为那天我的本地时区没有时间戳 02:00。所以我想知道python是否可以区分左/右手时间戳?

【问题讨论】:

  • 如果您确定时间戳严格增加,那么您可以parse them using pytz module
  • NonExistentTimeError 表明您的输入错误或您使用错误的时区来解释它。
  • 我一直在处理时间问题,但我从未听说过“左手”与“右手”或“左旋”与“右旋”等术语适用于时间戳。如果这是我从未听说过的已知事情,请指出您的消息来源。无论哪种方式,请准确解释您所说的这种区别是什么意思,以便其他人也可以学习。
  • @Matt:想想在一个时间间隔内记录的数据,比如 30 分钟,但数据采样系统只存储聚合值,通常是该时间间隔内的平均值、最大值、最小值。然后,例如 02:00 的时间戳是不明确的,因为它可能指的是区间 [01:30-02:00] 或区间 [02:00-02:30]。前一种情况是右手印章,后一种情况是左手印章。希望这能更清楚地解释它!
  • 当涉及时间时,通常使用半开间隔。示例:[01:30-2:00)[02:00-2:30)。这些将被您的术语“左手盖章”。我从未遇到过右手标记的时间间隔。想想您可能参加过的任何活动 - 结束时间是活动结束的时间,因此它不是该时间间隔的一部分。

标签: python dst timestamp-with-timezone


【解决方案1】:

我认为正确的方法是在进行任何算术运算时使用 UTC,并使用支持 DST 更改的 pytz 包从/到 UTC 转换。

【讨论】:

    【解决方案2】:

    pytz 允许您使用is_dst 参数选择夏令时转换之前/之后的UTC 偏移量:

    >>> import pytz
    >>> tz = pytz.timezone('Europe/Paris')                                                               
    >>> from datetime import datetime                                                                    
    >>> naive = datetime.strptime('2014-03-30 02:00:00', '%Y-%m-%d %H:%M:%S')                            
    >>> tz.localize(naive, is_dst=None)                            
    Traceback (most recent call last)
    ...
    NonExistentTimeError: 2014-03-30 02:00:00
    >>> tz.localize(naive) #XXX WRONG
    datetime.datetime(2014, 3, 30, 2, 0, tzinfo=<DstTzInfo 'Europe/Paris' CET+1:00:00 STD>)
    >>> tz.normalize(tz.localize(naive)) # you want this (default is after the transition)
    datetime.datetime(2014, 3, 30, 3, 0, tzinfo=<DstTzInfo 'Europe/Paris' CEST+2:00:00 DST>)
    >>> tz.localize(naive, is_dst=False) #XXX WRONG 
    datetime.datetime(2014, 3, 30, 2, 0, tzinfo=<DstTzInfo 'Europe/Paris' CET+1:00:00 STD>)
    >>> tz.localize(naive, is_dst=True) #XXX WRONG 
    datetime.datetime(2014, 3, 30, 2, 0, tzinfo=<DstTzInfo 'Europe/Paris' CEST+2:00:00 DST>)
    >>> tz.normalize(tz.localize(naive, is_dst=False)) # time corresponding to the offset
    datetime.datetime(2014, 3, 30, 3, 0, tzinfo=<DstTzInfo 'Europe/Paris' CEST+2:00:00 DST>)
    >>> tz.normalize(tz.localize(naive, is_dst=True)) # time corresponding to the offset
    datetime.datetime(2014, 3, 30, 1, 0, tzinfo=<DstTzInfo 'Europe/Paris' CET+1:00:00 STD>)
    

    【讨论】:

      猜你喜欢
      • 2021-11-06
      • 2012-12-23
      • 2013-02-16
      • 1970-01-01
      • 2016-04-05
      • 2014-01-07
      • 1970-01-01
      • 2023-01-08
      • 1970-01-01
      相关资源
      最近更新 更多