转换为UTC时间戳

Fed*_*rer 12 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
Run Code Online (Sandbox Code Playgroud)

我如何(在该代码中的任何点)将日期转换为UTC格式?我一直在通过这个看起来像是一个世纪的API而无法找到任何我可以工作的东西.有人可以帮忙吗?目前它正在把它变成东部时间,我相信(但我是GMT但想要UTC).

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

datetime1 = datetime.strptime(somestring, someformat)
timeInSeconds = calendar.timegm(datetime1.utctimetuple())
timeInMillis = timeInSeconds * 1000
Run Code Online (Sandbox Code Playgroud)

:)

Sil*_*ost 12

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

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

  • 仅适用于python 3. (4认同)
  • 为什么这只适用于Python 3?它似乎在2.7中运行良好. (2认同)

Mic*_*lon 6

您可能想要以下两者之一:

import time
import datetime

from email.Utils import formatdate

rightnow = time.time()

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

print formatdate(rightnow) 
Run Code Online (Sandbox Code Playgroud)

两个输出看起来像这样

2009-10-20 14:46:52.725000
Tue, 20 Oct 2009 14:46:52 -0000
Run Code Online (Sandbox Code Playgroud)


JJ *_*wax 5

我认为您可以使用以下utcoffset()方法:

utc_time = datetime1 - datetime1.utcoffset()
Run Code Online (Sandbox Code Playgroud)

文档使用此处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)
Run Code Online (Sandbox Code Playgroud)


use*_*287 5

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))`
Run Code Online (Sandbox Code Playgroud)

这会将本地时间转换为 UTC

time.mktime(time.localtime(calendar.timegm(utc_time)))
Run Code Online (Sandbox Code Playgroud)

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

如果使用 mktime 将 struct_time 转换为 seconds-since-the-epoch,则此转换在本地 timezone 中完成。没有办法告诉它使用任何特定的时区,甚至不仅仅是 UTC。标准的“时间”包始终假定时间在您的本地时区。