关于python:转换为UTC时间戳

Convert to UTC Timestamp

1
2
3
4
5
6
7
8
//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)。

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

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

:)


datetime.utcfromtimestamp可能是您正在寻找的:

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


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

1
utc_time = datetime1 - datetime1.utcoffset()

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

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

使用PyTZ:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
2
3
4
5
6
7
8
9
10
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

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

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

如果将struct_time转换为秒,那么使用mktime完成了epoch,这个
转换是在当地时区。没有办法告诉它使用任何特定的时区,甚至只是UTC。标准的"时间"套餐始终假定时间在您当地的时区。


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

1
2
3
4
5
6
7
8
9
10
11
import time
import datetime

from email.Utils import formatdate

rightnow = time.time()

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

print formatdate(rightnow)

两个输出看起来像这样

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