我正在构建一个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 documentation ,getRawOffset()
函数返回“添加到 UTC 以获得该时区标准时间的时间量(以毫秒为单位)”。这似乎是实例化 datetime.tzinfo
对象的一个很好的起点。
问题是,尽管我可以使用 getID()
方法的输出实例化一个,例如
import pytz
amsterdam = pytz.timezone('Europe/Amsterdam')
我不确定如何使用数字偏移实例化时区
,即使我将其转换为小时。例如,
pytz.timezone('+01:00')
产生UnknownTimeZoneError
。我将如何根据 UTC 的偏移量(以毫秒为单位)创建一个 datetime.tzinfo
对象? (我也对其他实现持开放态度,例如 Arrow 和 Pendulum )。
最佳答案
您的问题是时区同时包含偏移量和夏令时信息。
可能存在具有相同偏移量但夏令时不同的时区,因此仅靠偏移量不足以识别时区。
如果可能,您应该使用显示名称和/或 ID。
如果你做不到这一点,最好的办法是枚举所有时区,并根据哪些时区至少在一年中的部分时间有这种偏移量来获得一个候选名单。然后你就必须以某种方式选择一个。
关于python - 如何根据 UTC 的偏移(毫秒?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42001291/