如何从 UTC 的偏移量(毫秒?
How to construct a datetime tzinfo object from an offset from UTC in (milli)seconds?
我想构建一个 Python 应用程序,它将从 Android phone 接收时区信息,我想将其转换为 datetime tzinfo object (for example, as implemented by pytz ).
这个 Java 小程序显示 'sample' 可用的 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()
函数returns"the amount of time in milliseconds to add to UTC to get standard time in this time zone"。这似乎是实例化 datetime.tzinfo
对象的良好起点。
问题是,虽然我可以使用 getID()
方法的输出来实例化一个,例如
import pytz
amsterdam = pytz.timezone('Europe/Amsterdam')
我不确定如何使用数字偏移来实例化 timezone
,即使我将其转换为小时。例如,
pytz.timezone('+01:00')
产生 UnknownTimeZoneError
。我将如何根据与 UTC 的偏移量(以毫秒为单位)创建 datetime.tzinfo
对象? (我也对其他实现持开放态度,例如 Arrow and Pendulum)。
您的问题是时区包括偏移量和夏令时信息。
可以存在具有相同偏移量但夏令时不同的时区,因此仅偏移量不足以识别时区。
如果可能,您应该使用显示名称 and/or ID。
如果您不能这样做,最好的办法是枚举所有时区,并根据哪些时区至少在一年中的部分时间具有该偏移量来获得候选名单。那么你将不得不以某种方式选择一个。
我想构建一个 Python 应用程序,它将从 Android phone 接收时区信息,我想将其转换为 datetime tzinfo object (for example, as implemented by pytz ).
这个 Java 小程序显示 'sample' 可用的 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()
函数returns"the amount of time in milliseconds to add to UTC to get standard time in this time zone"。这似乎是实例化 datetime.tzinfo
对象的良好起点。
问题是,虽然我可以使用 getID()
方法的输出来实例化一个,例如
import pytz
amsterdam = pytz.timezone('Europe/Amsterdam')
我不确定如何使用数字偏移来实例化 timezone
,即使我将其转换为小时。例如,
pytz.timezone('+01:00')
产生 UnknownTimeZoneError
。我将如何根据与 UTC 的偏移量(以毫秒为单位)创建 datetime.tzinfo
对象? (我也对其他实现持开放态度,例如 Arrow and Pendulum)。
您的问题是时区包括偏移量和夏令时信息。
可以存在具有相同偏移量但夏令时不同的时区,因此仅偏移量不足以识别时区。
如果可能,您应该使用显示名称 and/or ID。
如果您不能这样做,最好的办法是枚举所有时区,并根据哪些时区至少在一年中的部分时间具有该偏移量来获得候选名单。那么你将不得不以某种方式选择一个。