【问题标题】:python3 epoch from timestamp string来自时间戳字符串的python3时代
【发布时间】:2017-09-30 08:47:41
【问题描述】:

我有这种类型的时间戳:

'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 转换器调用它来将时间戳列转换为纪元数。

self.dataset = loadtxt("data/dataset.csv", delimiter=",",converters={0: lambda d: self.str2timestamp(str(d))})

【问题讨论】:

    标签: python python-3.x datetime numpy timestamp


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-18
      • 2020-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多