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

前端 未结 4 1169
遥遥无期
遥遥无期 2021-01-03 04:08

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:0         


        
相关标签:
4条回答
  • 2021-01-03 04:20

    I am just guessing, but one hour difference can be not because of time zones, but because of daylight savings on/off.

    0 讨论(0)
  • 2021-01-03 04:32
    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 讨论(0)
  • 2021-01-03 04:34

    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.

    0 讨论(0)
  • 2021-01-03 04:35
    naive_utc_dt = parseddate.replace(tzinfo=None)
    timestamp = (naive_utc_dt - datetime(1970, 1, 1)).total_seconds()
    # -> 1247793660.0
    

    See more details in another answer to similar question.

    And back:

    utc_dt = datetime.utcfromtimestamp(timestamp)
    # -> datetime.datetime(2009, 7, 17, 1, 21)
    
    0 讨论(0)
提交回复
热议问题