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

I have a utc timestamp in 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 cannot return the correct time. An hour ahead is one if I use fromtimestamp (), and it is six hours ahead if I use utcfromtimestamp ()

Any tips?

Thank!

+5
python datetime unix-timestamp iso8601
Jul 03 '09 at 0:00
source share
4 answers

You can create a UTC struct_time with datetime.utctimetuple() and then convert this to a unix timestamp using calendar.timegm() :

 calendar.timegm(parseddate.utctimetuple()) 

This also applies to any daylight saving time because utctimetuple() normalizes this.

+13
Jul 03 '09 at 0:33
source share
— -

I just guess, but the time difference may not be due to time zones, but because of the transition to daylight saving time.

0
Jul 03 '09 at 0:09
source share
 naive_utc_dt = parseddate.replace(tzinfo=None) timestamp = (naive_utc_dt - datetime(1970, 1, 1)).total_seconds() # -> 1247793660.0 

See another answer to a similar question for details.

And back:

 utc_dt = datetime.utcfromtimestamp(timestamp) # -> datetime.datetime(2009, 7, 17, 1, 21) 
0
Nov 16 '12 at 19:50
source share
 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") 
0
Jun 25 '17 at 1:51 on
source share



All Articles