转换为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,这似乎是一个世纪,无法找到我可以使用的任何东西。有人可以帮忙吗?我相信目前正在将其转变为东部时间(但是我在格林尼治标准时间但想要UTC)。

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

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

:)


问题答案:
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

如果使用mktime将struct_time转换为自大纪元以来的秒数,则此转换 位于本地时区中
。没有办法告诉它使用任何特定的时区,甚至不使用UTC。标准的“时间”包始终假定时间在您当地的时区中。