从timedelta Python中提取分钟

2024-04-18 18:34:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带有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) )

不幸的是,我不太确定如何在不包括小时的情况下提取分钟


Tags: lambdadftimetimedeltatotalpddeltarh
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'))

使用^{}获取小时和分钟,并将其连接在一起:

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

相关问题 更多 >