python - 使用 timedelta 时小数位太多

标签 python python-3.x timedelta

我正在尝试以小时和分钟为单位查找时间,但我知道如何做到这一点的唯一方法是使用我在下面所做的事情。下面也是我的输出,如您所见,程序返回秒数和小数点。

代码:

def commercial_time (distance, speed_of_commercial):
    time = distance / speed_of_commercial
    seconds = time * 3600
    real = (datetime.timedelta(seconds = seconds))
    return real

输出:

9:46:04.352515

我的问题是,有什么办法可以去掉“.352515”吗? 如果可能的话,我也想隐藏秒数。

最佳答案

手动格式化timedelta:

def custom_format(td):
    minutes, seconds = divmod(td.seconds, 60)
    hours, minutes = divmod(minutes, 60)
    return '{:d}:{:02d}'.format(hours, minutes)

演示:

>>> from datetime import timedelta
>>> def custom_format(td):
...     minutes, seconds = divmod(td.seconds, 60)
...     hours, minutes = divmod(minutes, 60)
...     return '{:d}:{:02d}'.format(hours, minutes)
... 
>>> custom_format(timedelta(hours=9, minutes=46, seconds=4, microseconds=352515))
'9:46'

此方法确实忽略了.days 属性。如果您的时间增量超过 24 小时,请使用:

def custom_format(td):
    minutes, seconds = divmod(td.seconds, 60)
    hours, minutes = divmod(minutes, 60)
    formatted = '{:d}:{:02d}'.format(hours, minutes)
    if td.days:
        formatted = '{} day{} {}'.format(
            td.days, 's' if td.days > 1 else '', formatted)
    return formatted

演示:

>>> custom_format(timedelta(days=42, hours=9, minutes=46, seconds=4, microseconds=352515))
'42 days 9:46'
>>> custom_format(timedelta(days=1, hours=9, minutes=46, seconds=4, microseconds=352515))
'1 day 9:46'
>>> custom_format(timedelta(hours=9, minutes=46, seconds=4, microseconds=352515))
'9:46'

关于python - 使用 timedelta 时小数位太多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19234447/

相关文章:

python - Foundry Nuke 的重新格式化节点问题

python - 根据其他列 id 值创建新列 - Pandas

python - Pygame - 播放 youtube-dl 下载的 mp3 文件不起作用

python - 如何在 python 中对 datetime.timedelta 执行除法?

pandas - 如何设置列为日期索引?

python - 如何在 Matplotlib 的子图中单独绘制相同的图形?

python - python中将多个特定文本文件转换为CSV

python - 如何在 django 项目中运行 python 脚本?

python-3.x - 将带有标签的 pandas DF 写入 influxdb

python - numpy.longdouble dtype 的 timedelta 错误