转换为UTC时间戳(Convert to UTC Timestamp)

2019-08-21 20:48发布

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

:)

Answer 1:

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。 标准的“时间”包总是假定时间是在您的本地时区。



Answer 2:

datetime.utcfromtimestamp可能是你在找什么:

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


Answer 3:

我想你可以使用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)


Answer 4:

你可能想这两种中的一种:

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


文章来源: Convert to UTC Timestamp