2009-10-20 221 views
11
//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)。转换为UTC时间戳

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

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

:)

+0

你能指定什么时区'somestring'吗?它是UTC还是当地时区?如果'datetime1'不是UTC,'timegm(datetime1.utctimetuple())'将不起作用。 'utctimetuple()'不会*将它转换为UTC,除非给出一个知道的日期时间对象。 – jfs 2014-09-04 17:42:25

回答

2
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))` 

这如果struct_time转换为秒-因为-的历元是使用mktime完成本地时间转换为UTC

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

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

,这 转换在当地时区。没有办法告诉它使用任何特定的时区,甚至不仅仅是UTC。标准的“时间”包总是假定时间在您当地的时区。

+0

-1:'getDateAndTime()'是不相关的(它接受'seconds',问题首先要问的问题),它被打破了:实现不符合它的docstring。如果你有'utc_time',那么调用'calendar.timegm()'就足够了(本地时间,mktime都是不必要的,并且可能会产生错误的结果)。 – jfs 2014-09-04 17:40:09

8

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

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

仅适用于python 3。 – 2016-05-26 20:13:59

+2

为什么只适用于Python 3?它在2.7中似乎运行良好。 – sevko 2016-07-18 16:54:54

3

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

utc_time = datetime1 - datetime1.utcoffset() 

该文档给出这个例子使用astimezone()方法here

此外,如果你将要处理的时区,你可能想看看其中有许多有用的工具转换日期时间的成不同的时区(包括EST与UTC)

随着PyTZ的PyTZ library

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) 
+0

用于pytz的本地化()。注意:问题中的'datetime1'是一个天真的日期时间对象,即'datetime1.utcoffset()'返回'None'(你不能以这种方式得到UTC时间)。 – jfs 2014-09-04 17:46:54

1

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

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