我需要使用Python <= 2.7转换格式存储在变量中的时间
07/20-10:38:04.360700
这样的时间(自1970年1月1日午夜开始)
1405852684.360700
是最好导入时间模块,还是只是拆分并使用一些数学计算?
如果字符串日期与UTC有关,则:
In [31]: import datetime as DT
In [32]: text = '07/20-10:38:04.360700'
In [33]: date = DT.datetime.strptime('2014/'+text, '%Y/%m/%d-%H:%M:%S.%f')
In [34]: (date - DT.datetime(1970,1,1)).total_seconds()
Out[34]: 1405852684.3607
如果字符串date指的是相对于其他时区的日期,则可以pytz
在执行计算之前使用datetime感知datetime。例如,
import pytz
import datetime as DT
text = '07/20-10:38:04.360700'
tz = pytz.timezone('US/Eastern')
date = DT.datetime.strptime('2014/'+text, '%Y/%m/%d-%H:%M:%S.%f')
# interpret the date as coming from US/Eastern
date_tz = tz.localize(date)
epoch = DT.datetime(1970,1,1, tzinfo=pytz.utc)
timestamp = (date_tz - epoch).total_seconds()
print(repr(timestamp))
# 1405867084.3607
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句