3

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

代码:

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

4

2 回答 2

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 小时,请使用:

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'
于 2013-10-07T20:51:11.730 回答
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
于 2020-05-11T00:24:33.230 回答