如何以小时显示timedelta:min:sec? [英] How can I display timedelta in hours:min:sec?

查看:272
本文介绍了如何以小时显示timedelta:min:sec?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在导出一个timedeltas的列表到csv和天真的混乱了格式。我试过这个:

I am exporting a list of timedeltas to csv and the days really messes up the format. I tried this:

 while time_list[count] > datetime.timedelta(days = 1):
        time_list[count] = (time_list[count] - datetime.timedelta(days =  1)) + datetime.timedelta(hours = 24)

但它立即转换回天,并创建一个无限循环。

But it's instantly converted back into days and creates an infinite loop.

推荐答案

默认情况下, str() $ c> timedelta 将始终包括部分。在内部,该值总是标准化为天数,秒和微秒,因此没有时间将转换天数转换为小时,因为没有跟踪单独的小时组件。

By default the str() conversion of a timedelta will always include the days portion. Internally, the value is always normalised as a number of days, seconds and microseconds, there is no point in trying to 'convert' days to hours because no separate hour component is tracked.

如果您要以不同的方式格式化 timedelta()对象,您可以轻松地手动进行:

If you want to format a timedelta() object differently, you can easily do so manually:

def format_timedelta(td):
    minutes, seconds = divmod(td.seconds + td.days * 86400, 60)
    hours, minutes = divmod(minutes, 60)
    return '{:d}:{:02d}:{:02d}'.format(hours, minutes, seconds)

这将忽略任何微秒部分,但这是微不足道的:

This ignores any microseconds portion, but that is trivially added:

return '{:d}:{:02d}:{:02d}.{:06d}'.format(hours, minutes, seconds, td.microseconds)

演示:

>>> format_timedelta(timedelta(days=2, hours=10, minutes=20, seconds=3))
'58:20:03'
>>> format_timedelta(timedelta(hours=10, minutes=20, seconds=3))
'10:20:03'

这篇关于如何以小时显示timedelta:min:sec?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆