【问题标题】:Python: casting an integer into a datatime stampPython:将整数转换为日期时间戳
【发布时间】:2019-02-16 23:31:31
【问题描述】:

我发现转换以下列表l 非常困难:

l = [0, 1]

进入与以下数据帧df的索引对应的时间戳:

                 dt  val
2017-11-13 00:00:00  8
2017-11-13 01:00:00  17

理想的结果必须是:

l = [2017-11-13 00:00:00, 2017-11-13 01:00:00]

所以我可以在重叠df 的较长时间序列图中识别这两个时间步。

这样做的最佳方法是什么?我的尝试惨遭失败,我无法理解正确的时间戳格式:

index1 = pd.to_datetime(str(df.index[l[0]]), format='%Y-%m-%d %H:%M:%S')
index2 = pd.to_datetime(str(df.index[l[1]]), format='%Y-%m-%d %H:%M:%S')

这会引发错误:

ValueError: time data '2017-11-13 00:00:00' does not match format '%Y-%m-%d %H:%M:%S' (match)

【问题讨论】:

  • print(str(df.index[l[0]])) 输出什么?

标签: python pandas datetime timestamp time-series


【解决方案1】:

有几种方法,但这里有一种没有显式循环或指定格式的方法:

L = [0, 1]

datetime = pd.to_datetime('2017-11-13') + pd.to_timedelta(L, unit='h')

结果:

DatetimeIndex(['2017-11-13 00:00:00', '2017-11-13 01:00:00'], 
              type='datetime64[ns]', freq=None)

您的解决方案将不起作用,因为 str 不能以矢量化方式工作。

【讨论】:

    【解决方案2】:

    我认为需要fstrings 的列表理解:

    d = pd.to_datetime([f'2017-11-13 {x}:00:00' for x in l], format='%Y-%m-%d %H')
    print(d)
    
    DatetimeIndex(['2017-11-13 00:00:00', '2017-11-13 01:00:00'], 
                  dtype='datetime64[ns]', freq=None)
    

    性能(取决于真实数据):

    np.random.seed(2018)
    l = np.random.randint(12, size=1000).tolist()
    
    In [48]: %%timeit
        ...: d = pd.to_datetime([f'2017-11-13 {x}:00:00' for x in l], format='%Y-%m-%d %H')
    647 µs ± 2.45 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
    
    In [49]: %%timeit
        ...: d = pd.to_datetime('2017-11-13' + 
                 pd.Index(l).astype(str).str.zfill(2), format='%Y-%m-%d%H')
        ...: 
    4.43 ms ± 22 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
    

    【讨论】:

      猜你喜欢
      • 2012-04-02
      • 1970-01-01
      • 2019-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-17
      • 2021-11-22
      • 2012-05-15
      相关资源
      最近更新 更多