转换为UTC时间戳

时间:2009-10-20 14:32:36

标签: python datetime 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

:)

4 个答案:

答案 0 :(得分:10)

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

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

答案 1 :(得分:4)

我认为您可以使用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)

答案 2 :(得分:3)

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。标准的“时间”包始终假定时间在您当地的时区。

答案 3 :(得分: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