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

4 回答 4

17

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

>>> timestamp1 = time.mktime(datetime.now().timetuple())
>>> timestamp1
1256049553.0
>>> datetime.utcfromtimestamp(timestamp1)
datetime.datetime(2009, 10, 20, 14, 39, 13)
于 2009-10-20T14:37:12.333 回答
5

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

utc_time = datetime1 - datetime1.utcoffset()

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

Additionally, if you're going to be dealing with timezones, you might want to look into the PyTZ library which has lots of helpful tools for converting datetime's into various timezones (including between EST and UTC)

With 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)
于 2009-10-20T14:38:16.557 回答
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))`

This converts local time to UTC

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

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

If converting a struct_time to seconds-since-the-epoch is done using mktime, this conversion is in local timezone. There's no way to tell it to use any specific timezone, not even just UTC. The standard 'time' package always assumes that a time is in your local timezone.

于 2009-10-20T18:00:42.623 回答
4

You probably want one of these two:

import time
import datetime

from email.Utils import formatdate

rightnow = time.time()

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

print formatdate(rightnow) 

The two outputs look like this

2009-10-20 14:46:52.725000
Tue, 20 Oct 2009 14:46:52 -0000
于 2009-10-20T14:50:53.747 回答