【问题标题】:Combine initial date with time column in a pandas dataframe as datetime将熊猫数据框中的初始日期与时间列组合为日期时间
【发布时间】:2017-07-24 23:42:49
【问题描述】:

我正在阅读标题中包含年-月-日的文本日志文件,以及每行包含小时:分钟:秒的列。有点像这样:

Yr=17  Mn= 3 Dy= 3

19:22:59.894       52
19:24:12.130      106
19:24:13.241      107
...

我将日期作为datetime.date 对象:例如datetime.date(2017, 3, 3)。我有一个系列的时代:

df['Time'] = pd.to_datetime(df['Time strings'], format='%H:%M:%S.%f')

如何将标量日期与时间数组相加?

此外,其中一些日志会超过午夜。我想我需要使用numpy.unwrap() 之类的东西才能继续到下一个日期,但我不确定如何使用pandas.datetime

【问题讨论】:

    标签: python pandas datetime numpy


    【解决方案1】:

    您可以使用pd.to_timedelta,而不是在times上使用pd.to_datetime。然后,您可以简单地将该文件的日期时间添加到整个列中,它将被转换为日期时间列。

    示例

    times = ['4:23:12.12', '11:25:43.23', '14:29:55.42']
    
    df = pd.DataFrame(dict(times=times))
    
    df.times = pd.to_timedelta(df.times)
    
    df
    #             times
    # 0 04:23:12.120000
    # 1 11:25:43.230000
    # 2 14:29:55.420000
    
    file_date = datetime.date(2017, 3, 3)
    
    df.times += file_date
    
    df
    #                     times
    # 0 2017-03-03 04:23:12.120
    # 1 2017-03-03 11:25:43.230
    # 2 2017-03-03 14:29:55.420

    或者,您可以尝试在输入 parse_dates 时读取日期/时间。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-02
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-21
      相关资源
      最近更新 更多