问题 转换为UTC时间戳


//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

:)


7688
2017-10-20 14:32


起源

你能说明什么时区吗? somestring 在?是UTC还是当地时区? timegm(datetime1.utctimetuple()) 如果 datetime1 已经不是UTC了。 utctimetuple() 不 不 除非给出一个知道的datetime对象,否则将其转换为UTC。 - jfs


答案:


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转换为秒,那么使用mktime完成了这个时期,这个 转换是 在当地时区。没有办法告诉它使用任何特定的时区,甚至只是UTC。标准的“时间”包始终假定时间在您当地的时区。


2
2017-10-20 18:00



-1: getDateAndTime() 是无关的(它接受 seconds 问题是如何获得第一个问题)并且它被破坏了:实现与其文档字符串不对应。如果你有 utc_time 那就足够打电话了 calendar.timegm() (本地时间,mktime都是不必要的,可能会产生错误的结果)。 - jfs


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

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

8
2017-10-20 14:37



仅适用于python 3。 - mr-sk
为什么这只适用于Python 3?似乎在2.7中运行良好。 - sevko


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

utc_time = datetime1 - datetime1.utcoffset()

文档使用了这个例子 astimezone() 方法 这里

另外,如果您打算处理时区,您可能需要查看 PyTZ库 它有许多有用的工具,可以将日期时间转换为各种时区(包括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)

4
2017-10-20 14:38



为pytz的localize()+1。注意: datetime1 在这个问题中是一个天真的日期时间对象,即 datetime1.utcoffset() 回报 None (你无法以这种方式获得UTC时间)。 - jfs


你可能想要这两个中的一个:

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

1
2017-10-20 14:50