转换为Unix时间时如何指定时区(UTC)? (蟒蛇) [英] How to specify time zone (UTC) when converting to Unix time? (Python)
问题描述
在[9]中:mydate
出[9]:'2009-07- 17T01:21:00.000Z'
在[10]中:parseddate = iso8601.parse_date(mydate)
在[14]中:ti = time.mktime(parseddate.timetuple())
在[25]中:datetime.datetime.utcfromtimestamp(ti)
Out [25]:datetime.datetime(2009,7,17,7,21)
在[26 ]:datetime.datetime.fromtimestamp(ti)
Out [26]:datetime.datetime(2009,7,17,2,21)
在[27]中:ti
Out [27]:1247815260.0
在[28]中:parseddate
Out [28]:datetime.datetime(2009,7,17,1,21,tzinfo =< iso8601.iso8601.Utc对象在0x01D74C70>)
如您所见,我无法得到正确的时间。如果我使用fromtimestamp(),那么这个时间是一个小时,如果我使用utcfromtimestamp(),那么它会提前六个小时。
任何建议?
谢谢!
您可以创建一个 struct_time
在UTC与 datetime.utctimetuple()
,然后使用 calendar.timegm()
:
calendar。 timegm(parseddate.utctimetuple())
这也可以节省任何夏令时间的偏移量,因为 utctimetuple()
规范化这个。
I have a utc timestamp in the IS8601 format and am trying to convert it to unix time. This is my console session:
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>)
As you can see, I can't get the correct time back. The hour is ahead by one if i use fromtimestamp(), and it's ahead by six hours if i use utcfromtimestamp()
Any advice?
Thanks!
You can create an struct_time
in UTC with datetime.utctimetuple()
and then convert this to a unix timestamp with calendar.timegm()
:
calendar.timegm(parseddate.utctimetuple())
This also takes care of any daylight savings time offset, because utctimetuple()
normalizes this.
这篇关于转换为Unix时间时如何指定时区(UTC)? (蟒蛇)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!