【问题标题】:Convert to UTC Timestamp转换为 UTC 时间戳
【发布时间】:2009-10-20 14:32:35
【问题描述】:
//parses some string into that format.
datetime1 = datetime.strptime(somestring, "%Y-%m-%dT%H:%M:%S")

//gets the seconds from the above date.
timestamp1 = time.mktime(datetime1.timetuple())

//adds milliseconds to the above seconds.
timeInMillis = int(timestamp1) * 1000

我如何(在该代码中的任何位置)将日期转换为 UTC 格式?似乎一个世纪以来,我一直在研究 API,但找不到任何可以工作的东西。任何人都可以帮忙吗?我相信它目前正在变成东部时间(但是我在 GMT 但想要 UTC)。

编辑:我把答案交给了最接近我最终发现的人。

datetime1 = datetime.strptime(somestring, someformat)
timeInSeconds = calendar.timegm(datetime1.utctimetuple())
timeInMillis = timeInSeconds * 1000

:)

【问题讨论】:

  • 您能指定somestring 所在的时区吗?是UTC还是当地时区?如果datetime1 不是UTC,timegm(datetime1.utctimetuple()) 将不起作用。 utctimetuple() 是否将其转换为 UTC,除非给定一个可感知的日期时间对象。

标签: python datetime utc


【解决方案1】:

您可能想要以下两者之一:

import time
import datetime

from email.Utils import formatdate

rightnow = time.time()

utc = datetime.datetime.utcfromtimestamp(rightnow)
print utc

print formatdate(rightnow) 

两个输出是这样的

2009-10-20 14:46:52.725000
Tue, 20 Oct 2009 14:46:52 -0000

【讨论】:

    【解决方案2】:

    datetime.utcfromtimestamp 可能就是你要找的东西:

    >>> timestamp1 = time.mktime(datetime.now().timetuple())
    >>> timestamp1
    1256049553.0
    >>> datetime.utcfromtimestamp(timestamp1)
    datetime.datetime(2009, 10, 20, 14, 39, 13)
    

    【讨论】:

    • 仅适用于python 3。
    • 为什么只适用于 Python 3?它似乎在 2.7 中运行良好。
    • A -1 因为AttributeError: module 'datetime' has no attribute 'utcfromtimestamp'
    【解决方案3】:

    我认为你可以使用utcoffset() 方法:

    utc_time = datetime1 - datetime1.utcoffset()
    

    文档给出了一个使用astimezone() 方法here 的示例。

    此外,如果您要处理时区,您可能需要查看 PyTZ library,它有很多有用的工具可以将日期时间转换为各种时区(包括 EST 和 UTC 之间)

    使用 PyTZ:

    from datetime import datetime
    import pytz
    
    utc = pytz.utc
    eastern = pytz.timezone('US/Eastern')
    
    # Using datetime1 from the question
    datetime1 = datetime.strptime(somestring, "%Y-%m-%dT%H:%M:%S")
    
    # First, tell Python what timezone that string was in (you said Eastern)
    eastern_time = eastern.localize(datetime1)
    
    # Then convert it from Eastern to UTC
    utc_time = eastern_time.astimezone(utc)
    

    【讨论】:

    • +1 表示 pytz 的 localize()。注意:问题中的datetime1 是一个幼稚的日期时间对象,即datetime1.utcoffset() 返回None(您无法通过这种方式获得UTC 时间)。
    【解决方案4】:
    def getDateAndTime(seconds=None):
     """
      Converts seconds since the Epoch to a time tuple expressing UTC.
      When 'seconds' is not passed in, convert the current time instead.
      :Parameters:
          - `seconds`: time in seconds from the epoch.
      :Return:
          Time in UTC format.
    """
    return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(seconds))`
    

    这会将本地时间转换为 UTC

    time.mktime(time.localtime(calendar.timegm(utc_time)))
    

    http://feihonghsu.blogspot.com/2008/02/converting-from-local-time-to-utc.html

    如果将 struct_time 转换为 seconds-since-the-epoch 是使用 mktime 完成的,则此 转换是在本地时区。没有办法告诉它使用任何特定的时区,甚至不仅仅是 UTC。标准的“时间”包始终假定时间在您当地的时区。

    【讨论】:

    • -1: getDateAndTime() 是不相关的(它接受seconds 问题首先询问如何获取)并且它已损坏:实现与其文档字符串不对应。如果你有utc_time,那么调用calendar.timegm()就足够了(localtime,mktime都是不必要的,可能会产生错误的结果)。
    猜你喜欢
    • 2019-08-15
    • 2017-04-27
    • 2015-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多