简体   繁体   English

如何将 timedelta 转换为小时

[英]How to convert timedelta to hours

I have a timedelta Dataframe我有一个 timedelta Dataframe

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

but i want但我想要

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

How can I convert it?我怎样才能转换它?

Use, the combination of pd.to_timedelta , Series.dt.components , DataFrame.agg & Series.str.zfill :使用pd.to_timedeltaSeries.dt.componentsDataFrame.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)

Result:结果:

# print(df)

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

You could do as follows to convert a timedelta to the number of hours, minutes and seconds in the format you want:您可以执行以下操作将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

And to convert your dataframe, you can do something like this:要转换您的 dataframe,您可以执行以下操作:

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

Here is another approach:这是另一种方法:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM