时代转换未按预期工作

问题描述:

使用以下代码我想将输入日期和时间转换为时期。问题是,我得到一个划时代的输出,但是当我通过转换测试在线(http://www.epochconverter.com/),时代不转换的日期和时间,我输入:时代转换未按预期工作

date_time2 = '09.03.1999' + " " + "13:44:17.000000" 
pattern2 = '%d.%m.%Y %H:%M:%S.%f' 
epoch2 = int(time.mktime(time.strptime(date_time2, pattern2))) 
print epoch2 
+1

这对我的作品。你从在线转换器得到什么输出? – bernie

+1

当我运行该块时,我得到了921005057。但是,当我在在线转换器中添加时间戳时,它表示时间戳是GMT 18:44:17(注意输入时间已经是GMT)。它应该说格林尼治标准时间13:44:17 – user3498593

+0

你必须做这样的事情吗?:http://*.com/questions/19527351/python-how-to-convert-a-timezone-aware-timestamp-to -utc-without-know-if-dst – bernie

什么是发生在这里:

  • time.strptime产生一个time.struct_time,它与C的tm结构非常接近;
  • time.mktime的文档很清楚,它产生的的当地时间,而不是GMT时间的

因此,您需要一个将您的struct_time转换为GMT时间的函数。这样的功能在python中隐藏了一些,在calendar模块中。

尝试,而不是:

date_time2 = '09.03.1999' + " " + "13:44:17.000000" 
pattern2 = '%d.%m.%Y %H:%M:%S.%f' 

# get a time structure 
tm = time.strptime(date_time2, pattern2) 

# convert to gmt 
gmt_epoch = int(calendar.timegm(tm)) 

在这种情况下,我们结束了:

>>> gmt_epoch 
920987057 

堵到这一点,你已经给该网站产生的,这是GMT:周二,3月9日1999 13:44:17 GMT

+0

谢谢。我需要导入哪些额外的模块才能工作?当我运行它时,'time.struct_time'对象没有属性'tm_gmtoff'错误。我已经导入:从'进口日期时间日期时间从dateutil进口TZ 进口pytz' – user3498593

+0

我使用Python 2.7的方式 – user3498593

+0

DT,日期时间,timedelta 导入时间 从日期时间日期时间进口' 是tm_gmtoff'可用在Python 3.3及更高版本中:https://docs.python.org/3/library/time.html#time.struct_time请看我的答案。 – bernie

(我已经upvoted @ donkopotamus的答案在这里:https://*.com/a/38558696/42346

使用此问题:https://*.com/a/19527596/42346我们可以看到如何将当地时间转换为GMT。这需要pytz

import datetime as dt 
import pytz 

naive_date = dt.datetime.strptime('09.03.1999' + " " + "13:44:17.000000", 
            '%d.%m.%Y %H:%M:%S.%f') 
localtz = pytz.timezone('Hongkong') 
date_aware = localtz.localize(naive_date,is_dst=None) 
utc_date = date_aware.astimezone(pytz.utc) 
int(time.mktime(utc_date.utctimetuple())) 

结果:

920987057 

enter image description here