【问题标题】:How to specify time zone (UTC) when converting to Unix time? (Python)转换为 Unix 时间时如何指定时区 (UTC)? (Python)
【发布时间】:2010-11-07 19:36:01
【问题描述】:

我有一个 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>)

如您所见,我无法找回正确的时间。如果我使用 fromtimestamp() 会提前 1 小时,如果我使用 utcfromtimestamp() 会提前 6 小时

有什么建议吗?

谢谢!

【问题讨论】:

    标签: python datetime iso8601 unix-timestamp


    【解决方案1】:

    您可以使用datetime.utctimetuple() 在UTC 中创建struct_time,然后使用calendar.timegm() 将其转换为unix 时间戳:

    calendar.timegm(parseddate.utctimetuple())
    

    这也会处理任何夏令时偏移,因为utctimetuple() 会对此进行规范化。

    【讨论】:

    • timegm() 返回整数秒数。它忽略了几分之一秒。
    • 注意:不要混淆! utctimetuple()timetuple() 都返回相同的值!
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:
      naive_utc_dt = parseddate.replace(tzinfo=None)
      timestamp = (naive_utc_dt - datetime(1970, 1, 1)).total_seconds()
      # -> 1247793660.0
      

      another answer to similar question查看更多详情。

      然后返回:

      utc_dt = datetime.utcfromtimestamp(timestamp)
      # -> datetime.datetime(2009, 7, 17, 1, 21)
      

      【讨论】:

        【解决方案4】:
        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")
        

        【讨论】:

          猜你喜欢
          • 2023-03-27
          • 2016-06-11
          • 2021-04-25
          • 1970-01-01
          • 2014-07-15
          • 2017-03-17
          • 2014-05-06
          • 2013-10-23
          • 1970-01-01
          相关资源
          最近更新 更多