我在IS8601格式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>)

正如你所看到的,我不能得到正确的时间回来。小时是前方第1台如果我使用fromtimestamp(),并且它通过6小时是提前如果我使用utcfromtimestamp()

任何意见?

谢谢!

有帮助吗?

解决方案

可以创建在UTC与 struct_time 和一个datetime.utctimetuple()然后用它转换为一个Unix时间戳 calendar.timegm()

calendar.timegm(parseddate.utctimetuple())

这也需要照顾任何日光节约时间偏移,因为utctimetuple()标准化这一点。

其他提示

我只是猜测,但一次小时的时差可以是不因为,而是因为夏令时区的开/关。

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)
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")
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top