2017-05-22 22 views
1

我存储为字符串格式UTC时间戳列表如下:UTC字符串到UNIX时间转换蟒蛇

'20170124T1815' 

有Python中的功能,这些字符串到UNIX时间转换?我曾尝试过:

dt = datetime.datetime.utcnow() 
calendar.timegm(dt.utctimetuple()) 
(datetime.datetime.utcnow('20170127T2131').strftime('%Y-%m-%d %H:%M:%S')) 

但这些还没有为我工作,因为这些功能并不意味着采取论据。

回答

0

您需要将字符串 '20170124T1815' 转换为datetime实例:

import datetime 

dt = datetime.datetime.strptime('20170124T1815', '%Y%m%dT%H%M') 

然后用timestamp()方法转换为UNIX时间:

ut = dt.timestamp() 
# -> 1485281700.0 

documentation

datetime.timestamp()

Return POSIX timestamp corresponding to the datetime instance. The return value is a float similar to that returned by time.time() .

编辑

对于Python版本< 3.3,你可以使用:

ut = (dt - datetime.datetime(1970, 1, 1)).total_seconds() 

或者,你可以使用:

import time 

ut = time.mktime(dt.timetuple()) 

感谢Peter DeGlopper

+0

谢谢你,但我得到一个错误说AttributeError:'datetime.datetime'对象没有属性'时间戳' – coja7723

+0

我只有导入日期时间 – coja7723

+0

'timestamp()'在版本3.3中是新的。你使用哪个版本的Python? –