Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify time zone (UTC) when converting to Unix time? (Python)

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!

like image 272
rick Avatar asked Jul 03 '09 00:07

rick


People also ask

How convert UTC timestamp to Unix in Python?

DateTime to Unix timestamp in UTC Timezone In the time module, the timegm function returns a Unix timestamp. The timetuple() function of the datetime class returns the datetime's properties as a named tuple. To obtain the Unix timestamp, use print(UTC).

How do you convert UTC to time in Unix?

=(A1 / 86400) + 25569 Format the result cell for date/time, the result will be in GMT time (A1 is the cell with the epoch number). For other time zones: =((A1 +/- time zone adjustment) / 86400) + 25569.

How do you format UTC time in Python?

Getting the UTC timestamp datetime. now() to get the current date and time. Then use tzinfo class to convert our datetime to UTC. Lastly, use the timestamp() to convert the datetime object, in UTC, to get the UTC timestamp.

Is Unix time based on UTC?

Unix time is the number of seconds that have elapsed since 00:00:00 UTC on 1 January 1970, excluding leap seconds. This time is named the Unix epoch, because it is the start of the Unix time. Unix time is not a true representation of UTC, because leap seconds are not independently represented.


1 Answers

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.

like image 159
sth Avatar answered Oct 26 '22 22:10

sth