【问题标题】:How to construct a datetime tzinfo object from an offset from UTC in (milli)seconds?如何从 UTC 的偏移量(毫秒?
【发布时间】:2017-06-19 11:16:32
【问题描述】:

我正在寻找构建一个 Python 应用程序,该应用程序将从 Android 手机接收时区信息,我想将其转换为 datetime tzinfo 对象(例如,由 pytz 实现)。

这个 Java 小程序显示了TimeZone 可用格式的“样本”:

import java.util.TimeZone;

public class GetLocalTimeZone {

   public static void main(String []args) {
        TimeZone local_tz = TimeZone.getDefault();
        System.out.println(local_tz.getDisplayName());
        System.out.println(local_tz.getID());
        System.out.println(local_tz.getRawOffset());
   }
}

打印出来的

Central European Time
Europe/Amsterdam
3600000

根据TimeZone documentationgetRawOffset() 函数返回“添加到 UTC 以获得该时区的标准时间的时间量(以毫秒为单位)”。这似乎是实例化 datetime.tzinfo 对象的一个​​很好的起点。

问题是,虽然我可以使用getID() 方法的输出实例化一个,例如

import pytz
amsterdam = pytz.timezone('Europe/Amsterdam')

我不确定如何使用数字偏移量实例化 timezone,即使我将其转换为小时。例如,

pytz.timezone('+01:00')

产生UnknownTimeZoneError。我将如何从 UTC 的偏移量(以毫秒为单位)创建一个 datetime.tzinfo 对象? (我也对其他实现持开放态度,例如 ArrowPendulum)。

【问题讨论】:

    标签: python date datetime timezone pytz


    【解决方案1】:

    您的问题是时区同时包含偏移量和夏令时信息。

    可能存在偏移量相同但夏令时不同的时区,因此仅偏移量不足以识别时区。

    如果可能,您应该使用显示名称和/或 ID。

    如果您不能这样做,最好的办法是枚举所有时区,并根据哪些时区至少在一年中的部分时间具有该偏移量来获得一个候选名单。然后你必须以某种方式选择一个。

    【讨论】:

      猜你喜欢
      • 2013-07-28
      • 1970-01-01
      • 1970-01-01
      • 2013-08-28
      • 1970-01-01
      • 1970-01-01
      • 2011-11-09
      • 2017-12-11
      • 2022-12-24
      相关资源
      最近更新 更多