【问题标题】:How to get difference in hours between two timestamp columns in pandas data-frame如何获取熊猫数据框中两个时间戳列之间的小时数差异
【发布时间】:2021-11-15 20:13:08
【问题描述】:

我正在尝试获取以 '%H:%M:%S.%f' 格式给出的开始和结束时间戳数据之间的时间差,但出现值错误

Data-
|Start time|End time |
|----------|---------|
|02:48:00  | 03:03:00|
|02:48:00  | 03:03:00|
|22:21:00  | 23:40:00|
|22:21:00  | 23:40:00|
|01:30:00  | 02:54:00|
|09:10:00  | 10:13:00|
|05:31:00  | 06:28:00|
|23:09:00  | -1|
|16:09:00  | 17:29:00|

我正在尝试的代码

df3['timespent'] = pd.to_datetime(str(df3['End time'])) - pd.to_datetime(str(df3['Start Time']))

错误-

ValueError: ('Unknown string format:', '0     03:03:00\n1     03:03:00\n2     23:40:00\n3     23:40:00\n4     02:54:00\n        ...   \n86    21:13:00\n87    14:24:00\n88    19:57:00\n89    22:23:00\n90    10:53:00\nName: End time, Length: 91, dtype: object')*

【问题讨论】:

    标签: python python-3.x pandas datetime timedelta


    【解决方案1】:

    如果值已经在 DataFrame 中,您可能只需要去掉空格 -

    pd.to_datetime(df3['End time'].str.strip()) - pd.to_datetime(df3['Start Time'].str.strip()) 
    

    如果格式未被自动识别 - 您可以将格式字符串传递给 to_datetime 函数

    【讨论】:

    • 嗨 Mortz,我使用了你的代码,但收到错误 - 只能将 .str 访问器与字符串值一起使用!
    • 虽然开始和结束时间的格式只有object/str格式
    • 出错的地方 - 打印出df3.dtypes的值
    • 显示的数据类型:开始时间-对象,结束时间-对象,dtype:对象
    • 此错误是由于结束时间列中的异常值 (-1) 造成的吗?
    【解决方案2】:

    首先,看到你的数据,我建议申请pd.to_timedelta。这些可以用来计算开始和结束之间的Timedelta,然后最终访问时间的seconds字段。

    话虽如此,您的字符串可能需要对.strip() 进行一些剥离才能获得代码中显示的格式。

    import pandas as pd
    from datetime import timedelta
    
    df = pd.DataFrame({
        'start' : ["20:15:12", "08:08:08", "23:59:58"], 
        'end' : ["20:25:52", "11:11:11", "00:01:01"]
    })
    
    
    # convert 'start' and 'end' to timedeltas and then substract start from end
    df['diff'] = df.apply(pd.to_timedelta).apply(lambda x: x.end - x.start,axis=1)
    # correct those that cross midnight
    correct24h = timedelta(hours=24)
    df['diff'] = df['diff'].apply(lambda x: x + correct24h if x.delta < 0 else x)
    
    # calculate hours from seconds
    df['diff_hours'] = df['diff'].dt.seconds / 60 / 60
    
    df
          start       end            diff  diff_hours
    0  20:15:12  20:25:52 0 days 00:10:40    0.177778
    1  08:08:08  11:11:11 0 days 03:03:03    3.050833
    2  23:59:58  00:01:01 0 days 00:01:03    0.017500
    

    【讨论】:

    • 再次查看其他答案和讨论-您的问题更多是您如何读取数据并构建数据框问题。它来自文件吗?它看起来怎么样?
    • 它来自我导入的 excel 文件,以小时和秒格式给出 'hh:ss'
    • 一些示例代码会花很多时间。例如。你的进口声明怎么样?另外,我猜您发布的数据示例不是python输出语句。
    • 我有一周的每日 excel 文件,所以我将所有 excel 文件附加到一个使用代码中 - all_data = [] for f in glob.glob("...path.../*.xlsx "): all_data.append(pd.read_excel(f)) df1 = pd.concat(all_data, ignore_index=True)
    猜你喜欢
    • 2020-08-05
    • 2020-12-02
    • 2018-04-18
    • 2018-02-23
    • 1970-01-01
    • 2022-10-02
    • 2019-08-23
    • 1970-01-01
    • 2020-05-31
    相关资源
    最近更新 更多