如何在转换为Unix时间时指定时区(UTC)?(Python)

5

我有一个以ISO8601格式表示的UTC时间戳,现在想将它转换为Unix时间。这是我的命令行会话记录:

In [9]: mydate
Out[9]: '2009-07-17T01:21:00.000Z'
In [10]: parseddate = iso8601.parse_date(mydate)

In [14]: ti = time.mktime(parseddate.timetuple())

In [25]: datetime.datetime.utcfromtimestamp(ti)
Out[25]: datetime.datetime(2009, 7, 17, 7, 21)
In [26]: datetime.datetime.fromtimestamp(ti)
Out[26]: datetime.datetime(2009, 7, 17, 2, 21)

In [27]: ti
Out[27]: 1247815260.0
In [28]: parseddate
Out[28]: datetime.datetime(2009, 7, 17, 1, 21, tzinfo=<iso8601.iso8601.Utc object at 0x01D74C70>)

如您所见,我无法获得正确的时间。如果我使用fromtimestamp()函数,小时数会超前一个小时,而如果我使用utcfromtimestamp()函数,则会超前六个小时。

您有什么建议吗?

谢谢!

4个回答

13
您可以使用datetime.utctimetuple()在UTC中创建一个struct_time,然后使用calendar.timegm()将其转换为Unix时间戳:
calendar.timegm(parseddate.utctimetuple())

这也解决了任何夏令时偏移的问题,因为utctimetuple()会进行归一化处理。


timegm() 返回整数秒数。它忽略秒的小数部分。 - jfs
注意:不要被搞混了! utctimetuple()timetuple() 返回的值是相同的! - Leonid Ganeline

1
naive_utc_dt = parseddate.replace(tzinfo=None)
timestamp = (naive_utc_dt - datetime(1970, 1, 1)).total_seconds()
# -> 1247793660.0

请查看类似问题的另一个答案以获取更多详细信息。

返回:

utc_dt = datetime.utcfromtimestamp(timestamp)
# -> datetime.datetime(2009, 7, 17, 1, 21)

1
我只是猜测,但一个小时的差异可能不是由于时区,而是因为夏令时开/关。

0
import time
import datetime
import calendar

def date_time_to_utc_epoch(dt_utc):         #convert from utc date time object (yyyy-mm-dd hh:mm:ss) to UTC epoch
    frmt="%Y-%m-%d %H:%M:%S"
    dtst=dt_utc.strftime(frmt)              #convert datetime object to string
    time_struct = time.strptime(dtst, frmt) #convert time (yyyy-mm-dd hh:mm:ss) to time tuple
    epoch_utc=calendar.timegm(time_struct)  #convert time to to epoch
    return epoch_utc

#----test function --------
now_datetime_utc = int(date_time_to_utc_epoch(datetime.datetime.utcnow()))
now_time_utc = int(time.time())

print (now_datetime_utc)
print (now_time_utc)

if now_datetime_utc == now_time_utc : 
    print ("Passed")  
else : 
    print("Failed")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接