【问题标题】:Extract minute from timedelta - Python从 timedelta 中提取分钟 - Python
【发布时间】:2020-08-24 11:36:37
【问题描述】:

我有一个包含 timedelta 的列,我想创建一个额外的列,从 timedelta 列中提取小时和分钟。

df

time_delta          hour_minute
02:51:21.401000     2h:51min
03:10:32.401000     3h:10min
08:46:43.401000     08h:46min

这是我迄今为止尝试过的:

df['rh'] = df.time_delta.apply(lambda x: round(pd.Timedelta(x).total_seconds() \
                          % 86400.0 / 3600.0) )

不幸的是,我不太确定如何提取不包含在内的会议记录。小时

【问题讨论】:

  • 您的time_delta 列中的dtype 是什么?你能打印df['time_delta'].dtypes的输出吗?
  • 这能回答你的问题吗? Formatting timedelta objects

标签: python pandas


【解决方案1】:

使用Series.dt.components 获取小时和分钟并加入:

td = pd.to_timedelta(df.time_delta).dt.components
df['rh'] = (td.hours.astype(str).str.zfill(2) + 'h:' + 
            td.minutes.astype(str).str.zfill(2) + 'min')
print (df)
        time_delta hour_minute         rh
0  02:51:21.401000    2h:51min  02h:51min
1  03:10:32.401000    3h:10min  03h:10min
2  08:46:43.401000   08h:46min  08h:46min

如果小时的可能值更像是 24 小时,还需要添加天数:

print (df)
        time_delta hour_minute
0  02:51:21.401000    2h:51min
1  03:10:32.401000    3h:10min
2  28:46:43.401000   28h:46min

td = pd.to_timedelta(df.time_delta).dt.components
print (td)
   days  hours  minutes  seconds  milliseconds  microseconds  nanoseconds
0     0      2       51       21           401             0            0
1     0      3       10       32           401             0            0
2     1      4       46       43           401             0            0

df['rh'] = ((td.days * 24 + td.hours).astype(str).str.zfill(2) + 'h:' + 
            td.minutes.astype(str).str.zfill(2) + 'min')
print (df)

        time_delta hour_minute         rh
0  02:51:21.401000    2h:51min  02h:51min
1  03:10:32.401000    3h:10min  03h:10min
2  28:46:43.401000   28h:46min  28h:46min

【讨论】:

    【解决方案2】:

    另见this post,它定义了函数

    def strfdelta(tdelta, fmt):
        d = {"days": tdelta.days}
        d["hours"], rem = divmod(tdelta.seconds, 3600)
        d["minutes"], d["seconds"] = divmod(rem, 60)
        return fmt.format(**d)
    

    然后,例如

    strfdelta(pd.Timedelta('02:51:21.401000'), '{hours}h:{minutes}min')
    

    给出'2h:51min'。 对于您的完整数据框

    df['rh'] = df.time_delta.apply(lambda x: strfdelta(pd.Timedelta(x), '{hours}h:{minutes}min'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多