获取 datetime.datetime.fromtimestamp() 使用的时区 [英] Get timezone used by datetime.datetime.fromtimestamp()

查看:84
本文介绍了获取 datetime.datetime.fromtimestamp() 使用的时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能,如果是,如何获取 datetime.datetime 使用的时区(即 UTC 偏移量或具有该偏移量的 datetime.timezone 实例).fromtimestamp()POSIX 时间戳(自纪元以来的秒数)转换为 datetime 对象?

datetime.datetime.fromtimestamp() 将 POSIX 时间戳转换为简单的 datetime 对象(即没有 tzinfo),但这样做使用系统的语言环境将其调整为本地时区和当时有效的 UTC 偏移量.

例如,使用日期 2008-12-27 午夜 UTC(自纪元以来的 40 * 356 * 86400 秒):

<预><代码>>>>datetime.datetime.fromtimestamp(40 * 356 * 86400)datetime.datetime(2008, 12, 27, 1, 0)

那个时间戳在凌晨 1 点被转换为一个 datetime 对象(当时是在 CET/CEST 时区).100天后,结果如下:

<预><代码>>>>datetime.datetime.fromtimestamp((40 * 356 + 100) * 86400)datetime.datetime(2009, 4, 6, 2, 0)

现在是凌晨 2 点.这是因为到那时,DST 是活跃的.

我希望 datetime.datetime.fromtimestamp() 会设置它在返回的 datetime 实例中使用的 tzinfo,但它没有.

解决方案

datetime.fromtimestamp(ts) 将自纪元以来的秒数"转换为表示本地时间的简单日期时间对象.tzinfo 在这种情况下总是 None.

本地时区过去可能有不同的 UTC 偏移量.在某些提供历史时区数据库访问权限的系统上,fromtimestamp() 可能会将其考虑在内.

获取fromtimestamp()使用的UTC偏移量:

utc_offset = fromtimestamp(ts) - utcfromtimestamp(ts)

另请参阅在 Python 中获取计算机的 utc 偏移量.

Is it possible, and if yes, how, to get the time zone (i.e. the UTC offset or a datetime.timezone instance with that offset) that is used by datetime.datetime.fromtimestamp() to convert a POSIX timestamp (seconds since the epoch) to a datetime object?

datetime.datetime.fromtimestamp() converts a POSIX timestamp to a naive datetime object (i.e. without a tzinfo), but does so using the system's locale to adjust it to the local timezone and the UTC offset that was in effect at that time.

For example, using the date 2008-12-27 midnight UTC (40 * 356 * 86400 seconds since the epoch):

>>> datetime.datetime.fromtimestamp(40 * 356 * 86400)
datetime.datetime(2008, 12, 27, 1, 0)

That timestamp is converted to a datetime object at 1 o'clock in the morning (which it was at that time, here in an CET/CEST timezone). 100 days later, this is the result:

>>> datetime.datetime.fromtimestamp((40 * 356 + 100) * 86400)
datetime.datetime(2009, 4, 6, 2, 0)

Which is 2 o'clock in the morning. This is because by then, DST was active.

I'd expected that datetime.datetime.fromtimestamp() would set the tzinfo it uses in the returned datetime instance, but it doesn't.

解决方案

datetime.fromtimestamp(ts) converts "seconds since the epoch" to a naive datetime object that represents local time. tzinfo is always None in this case.

Local timezone may have had a different UTC offset in the past. On some systems that provide access to a historical timezone database, fromtimestamp() may take it into account.

To get the UTC offset used by fromtimestamp():

utc_offset = fromtimestamp(ts) - utcfromtimestamp(ts)

See also, Getting computer's utc offset in Python.

这篇关于获取 datetime.datetime.fromtimestamp() 使用的时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆