将字典的值转换为时间戳格式

Mat*_*eja 0 python datetime dictionary timestamp type-conversion

我有这样的字典:

>>print xdict 
{'time': [(2015, 6, 3, 10, 41, 3), (2015, 6, 3, 20, 32, 21), ..., ...]}
Run Code Online (Sandbox Code Playgroud)

是否可以将这些值转换为时间戳格式?我想像这样:

print xdict
{'time': [1433320863.0, 1433356341.0, ..., ...]}
Run Code Online (Sandbox Code Playgroud)

jfs*_*jfs 5

您的时间元组不代表UTC时间。如果这是您的本地时区,并且对应时间的utc偏移规则与现在相同,或者如果C时区库可以访问平台上的历史时区数据库,则可以将时间元组传递给以time.mktime()获取“秒”从时代开始”:

#!/usr/bin/env python
import time

x = {'time': [(2015, 6, 3, 10, 41, 3), (2015, 6, 3, 20, 32, 21)]}
x['time'] = [time.mktime(tt + (-1,)*3) for tt in x['time']]
Run Code Online (Sandbox Code Playgroud)

否则,您应该pytz用来访问所有平台上的tz数据库,并计算与输入时间元组相对应的正确“自纪元以来的秒数”(POSIX时间戳):

#!/usr/bin/env python
from datetime import datetime
import pytz # $ pip install pytz
import tzlocal # $ pip install tzlocal

local_timezone = tzlocal.get_localzone() # pytz tzinfo representing local time
epoch = datetime(1970, 1, 1, tzinfo=pytz.utc)
x = {'time': [(2015, 6, 3, 10, 41, 3), (2015, 6, 3, 20, 32, 21)]}
x['time'] = [(local_timezone.localize(datetime(*tt), is_dst=None) - epoch).total_seconds()
             for tt in x['time']]
Run Code Online (Sandbox Code Playgroud)

  • 感谢您的回答并为Stack Overflow做出了贡献,但是请重新考虑该问题,因为根据[help / on-topic],它似乎是不合时宜的。回答离题的问题看起来可以问这样的问题,事实并非如此。题外的问题可能会被关闭,然后被删除,这将使您的贡献无效! (4认同)
  • @Kyll:我不认为这个问题是题外话。如果您不发布模板注释并提供特定于此问题的原因,则适合您。 (4认同)