【问题标题】:converting mountain standard time to eastern standard time in python在python中将山区标准时间转换为东部标准时间
【发布时间】:2012-10-29 00:41:04
【问题描述】:

我有一个时间 datetime 对象..它同时具有日期和时间..

例如

    d = (2011,11,1,8,11,22)  (24 hour time time format)

但是这个时间戳是山区标准时间..(亚利桑那州凤凰城)

现在我想在 EST 中转换这个时间......

现在这只是时间增量调整..

但是还有这个夏令时问题。

我想知道是否有一种内置方法来处理夏令时以调整时区..

【问题讨论】:

    标签: python datetime timezone


    【解决方案1】:

    基于pytz docs 中的示例,该示例将天真的日期时间对象从一个时区转换为另一个时区:

    from datetime import datetime
    import pytz
    
    def convert(naive_dt, from_tz, to_tz, is_dst=None):
        """Convert naive_dt from from_tz timezone to to_tz timezone.
    
        if is_dst is None then it raises an exception for ambiguous times
        e.g., 2002-10-27 01:30:00 in US/Eastern
        """
        from_dt = from_tz.localize(naive_dt, is_dst=is_dst)
        return to_tz.normalize(from_dt.astimezone(to_tz))
    
    ph_tz = pytz.timezone('America/Phoenix')
    east_tz = pytz.timezone('US/Eastern')
    from_naive_dt = datetime(2011, 11, 1, 8, 11, 22)
    east_dt = convert(from_naive_dt, ph_tz, east_tz)
    
    def p(dt):
        print(dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'))
    
    p(east_dt)  # -> 2011-11-01 11:11:22 EDT-0400
    

    以下是来自 pytz 文档的模棱两可时间示例:

    ambiguous_dt = datetime(2002, 10, 27, 1, 30)
    p(convert(ambiguous_dt, east_tz, pytz.utc, is_dst=True))
    p(convert(ambiguous_dt, east_tz, pytz.utc, is_dst=False))
    p(convert(ambiguous_dt, east_tz, pytz.utc, is_dst=None)) # raise exception
    assert 0 # unreachable
    

    输出:

    2002-10-27 05:30:00 UTC+0000 # ambiguous_dt is interpreted as EDT-0400
    2002-10-27 06:30:00 UTC+0000 # ambiguous_dt is interpreted as EST-0500
    pytz.exceptions.AmbiguousTimeError: 2002-10-27 01:30:00
    

    【讨论】:

      【解决方案2】:

      使用pytz 进行时区转换。 pytz 考虑到夏令时检查this。你需要一个辅助函数,比如:

      def convert(dte, fromZone, toZone):
          fromZone, toZone = pytz.timezone(fromZone), pytz.timezone(toZone)
          return fromZone.localize(dte, is_dst=True).astimezone(toZone)
      

      【讨论】:

      • toZone.normalize() 呼叫可能丢失。 is_dst=True 在 DST 转换期间有 50% 的时间是错误的
      【解决方案3】:

      您要查找的库是 pytz,特别是 localize() 方法。

      Pytz 不在标准库中,但您可以通过 pip 或 easy_install 获得它。

      【讨论】:

      • tz.localize() 将 tz 中的原始日期时间对象转换为 tz 中的感知日期时间对象。它不会从一个时区转换到另一个时区。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-12
      • 2021-01-16
      • 1970-01-01
      • 2020-02-04
      • 2022-01-26
      • 2014-01-23
      • 1970-01-01
      相关资源
      最近更新 更多