【问题标题】:Python utcfromtimestamp and fromtimestamp output same value?Python utcfromtimestamp 和 fromtimestamp 输出相同的值?
【发布时间】:2016-08-22 07:38:51
【问题描述】:
我有一个 Python+Django 应用程序,它以 UTC 格式存储所有内容,并在设置中有 TIME_ZONE = 'UTC' 和 USE_TZ = True。转换 POSIX 时间戳时,fromtimestamp 两种风格的输出相同:
start_seconds = 1461798000000 / 1000.0
start = datetime.datetime.utcfromtimestamp(start_seconds)
print('With utc: %s' % start)
>>>> With utc: 2016-04-27 23:00:00
start2 = datetime.datetime.fromtimestamp(start_seconds)
print('Without utc: %s' % start2)
>>>> Without utc: 2016-04-27 23:00:00
为什么会这样?
【问题讨论】:
标签:
python
django
python-2.7
datetime
django-1.9
【解决方案1】:
如果fromtimestamp() 和ucfromtimestamp() 返回相同的值,则表示本地时区在给定时间的UTC 偏移量为零。 Django 设置您的本地时区 (TZ envvar),以反映您的情况下为 UTC 的 TIME_ZONE 设置,并且(显然)UTC 偏移量在 UTC 中为零。
获取与给定 POSIX 时间戳对应的时区感知日期时间对象:
from datetime import datetime, timedelta
import pytz
dt = datetime(1970, 1, 1, tzinfo=pytz.utc) + timedelta(seconds=start_seconds)
转换 Unix 时间:
dt = datetime.fromtimestamp(start_seconds, pytz.utc)
在极端情况下,这些值可能会有所不同。
【解决方案2】:
运行您的代码给了我预期的结果,它们是相对于各自时区的原始日期时间。根据 epochconverter,您提供的时间戳是 2016-04-27 23:00:00 UTC
In[23]: import datetime
In[24]: start_seconds = 1461798000000 / 1000.0
In[25]: start = datetime.datetime.utcfromtimestamp(start_seconds)
In[26]: print('With utc: %s' % start)
With utc: 2016-04-27 23:00:00 # Correct UTC time
In[27]: start2 = datetime.datetime.fromtimestamp(start_seconds)
In[28]: print('Without utc: %s' % start2)
Without utc: 2016-04-27 19:00:00 # Correct EDT time (my local timezone)