转换为UTC时间戳

2024-06-28 19:07:30 发布

您现在位置:Python中文网/ 问答频道 /正文

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

:)


Tags: thedatetimestring时间someparsesaboveutc
3条回答

^{}可能是您要找的:

>>> timestamp1 = time.mktime(datetime.now().timetuple())
>>> timestamp1
1256049553.0
>>> datetime.utcfromtimestamp(timestamp1)
datetime.datetime(2009, 10, 20, 14, 39, 13)
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将结构时间转换为自纪元完成以来的秒,则 在本地时区中转换为。没有办法告诉它使用任何特定的时区,甚至不只是UTC。标准的“time”包总是假设时间在本地时区内。

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

utc_time = datetime1 - datetime1.utcoffset()

文档给出了一个使用astimezone()方法here的例子。

另外,如果您要处理时区,您可能需要查看PyTZ library,它有很多有用的工具,可以将datetime转换为各种时区(包括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)

相关问题 更多 >