如何将timedelta转换为小时

How to convert timedelta to hours

我有一个 timedelta 数据框

JC time
1 3days 21:02:05
2 1days 23:50:07
3 6days 19:28:36

但我想要

1 93:02:05
2 47:50:07
3 163:28:36

如何转换?

您可以按如下方式将 timedelta 转换为所需格式的小时、分钟和秒数:

def convert_to_hours(delta):
    total_seconds = delta.total_seconds()
    hours = str(int(total_seconds // 3600)).zfill(2)
    minutes = str(int((total_seconds % 3600) // 60)).zfill(2)
    seconds = str(int(total_seconds % 60)).zfill(2)
    return f"{hours}:{minutes}:{seconds}"

delta = timedelta(days=3, hours=21, minutes=2, seconds=5)
# 3 days, 21:02:05

convert_to_hours(delta)
# 93:02:05

要转换数据框,您可以这样做:

df["time"] = df["time"].apply(convert_to_hours)

使用,pd.to_timedelta, Series.dt.components, DataFrame.agg & Series.str.zfill的组合:

d = pd.to_timedelta(df['time']).dt.components[['days', 'hours', 'minutes', 'seconds']]
d['hours'] = d['hours'].add(d.pop('days') * 24)

df['time'] = d.astype(str).agg(lambda s: ':'.join(s.str.zfill(2)), axis=1)

结果:

# print(df)

   JC       time
0   1   93:02:05
1   2   47:50:07
2   3  163:28:36

这是另一种方法:

def strf_delta(td):
    h, r = divmod(int(td.total_seconds()), 60*60)
    m, s = divmod(r, 60)
    h, m, s = (str(x).zfill(2) for x in (h, m, s))
    return f"{h}:{m}:{s}"

d['time'].apply(strf_delta)