2016-04-27 60 views
0

我有一个Python + Django应用程序,它以UTC存储所有内容,并且在设置中有TIME_ZONE = 'UTC'USE_TZ = True。当转换POSIX时间戳我得到的fromtimestamp两个口味的输出相同:Python utcfromtimestamp和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 

为什么会变成这样?

回答

1

如果fromtimestamp()ucfromtimestamp()返回相同的值,则意味着本地时区具有零UTC在给定时间偏移。 Django设置你当地的时区(TZ envvar),以反映在你的情况下是UTC的TIME_ZONE设置,并且(明显)UTC的utc偏移量为零。

要获得对应于给定POSIX时间戳的时区感知DateTime对象:

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) 

的值可能在边缘情况有所不同。

+0

感谢您的解释,也代码片段。 – felizuno

0

运行你的代码给了我预期的结果,这些结果是天真的日期时间在他们各自时区的偏移量。据epochconverter您提供的时间戳是2016年4月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) 
相关问题