我有这种类型的时间戳:
'Mon Oct 31 2016 23:00:00 GMT+0000 (UTC)'
从str转换为unix的模式代码(不工作):
def str2timestamp(self,timestr,epoch=datetime.datetime.fromtimestamp(0)):
timestr = timestr.replace('GMT+0000 (UTC)', '').strip()
dt = datetime.datetime.strptime(timestr.strip(), '%a %b %d %Y %H:%M:%S')
return (dt - epoch).total_seconds()
我收到此错误:
ValueError:时间数据“b'Mon Oct 31 2016 23:00:00'”格式'%a%b%d%Y%H:%M:%S
我从numpy转换器调用它将timestamp列转换为epoch-number。
self.dataset = loadtxt("data/dataset.csv", delimiter=",",converters={0: lambda d: self.str2timestamp(str(d))})
答案 0 :(得分:1)
这是一个更简单的实现,可以满足您的需求:
<强>代码:强>
import datetime as dt
def str2timestamp(timestr, epoch=dt.datetime.fromtimestamp(0)):
stamp = dt.datetime.strptime(timestr.strip()[4:24], '%b %d %Y %H:%M:%S')
return (stamp - epoch).total_seconds()
测试代码:
print(str2timestamp('Mon Oct 31 2016 23:00:00 GMT+0000 (UTC)'))
<强>结果:强>
1477983600.0