使用timedelta时小数位太多

时间:2013-10-07 20:48:49

标签: python python-3.x timedelta

我试图在小时和分钟内找到时间但是,我知道如何做的唯一方法是使用我在下面所做的。下面也是我的输出,正如你所看到的,程序返回秒数和之后的小数。

CODE:

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”? 如果可能的话,我也想隐藏秒数。

2 个答案:

答案 0 :(得分:6)

手动格式化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小时的timedeltas,请使用:

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'

答案 1 :(得分:0)

使用str()将时间差转换为字符串,然后使用.split('.')在小数点的两侧分开。然后用[0]将第一部分保留在小数点前:

您的示例与最后一行唯一的不同:

import time
import datetime

def commercial_time (distance, speed_of_commercial):
    time = distance / speed_of_commercial
    seconds = time * 3600
    real = (datetime.timedelta(seconds = seconds))
    return str(real).split('.')[0]

然后:

print( commercial_time( 10 , 1.025 ) )

生成:

9:45:21