在 Python 内将秒转换为天、小时、分钟和秒

Converting seconds into days, hours, minutes & seconds in Python

我有一个函数,可以将 returns 秒转换为天、小时、分钟和秒。但是我需要 但是,如果输出为 0,则不打印。例如,如果我输入 176400 秒,我希望输出为“2 天 1 小时”而不是“2 天、2 小时、0 分钟、0 秒”。

到目前为止我做了:

sec = int(input("Enter time in Seconds: "))
temp = sec
day = sec // 86400
sec %= 86400
hour = sec // 3600
sec %= 3600
mins = sec // 60
sec %= 60

if day >= 1:
    print(f'time in minutes is {day}days {hour}hour {mins}min {sec}sec')

elif hour >= 1:
    if mins == 0 and sec == 0:
        print(f'time in minutes is {hour}hour')
    elif mins == 0:
        print(f'time in minutes is {hour}hour {sec}sec')
    elif sec == 0:
        print(f'time in minutes is {hour}hour {mins}min')
    else:
        print(f'time in minutes is {hour}hour {mins}min {sec}sec')

elif mins >= 1:
    if sec == 0:
        print(f'time in minutes is {mins}min')
    else:
        print(f'time in minutes is {mins}min {sec}sec')

elif sec >= 1:
    print(f'time sec == {sec} sec')

我可以继续这段代码使用一堆“if”语句,但是有没有更短的方法来做到这一点?

IIUC,你想要更短的方式然后你可以使用 datetime.timedelta 如下:

import datetime

sec = int(input('Enter the number of seconds: '))

print(datetime.timedelta(seconds=sec))

输出:

Enter the number of seconds: 86600
1 day, 0:03:20

您可以添加这些行以获得您想要的内容:

import datetime
sec = int(input('Enter the number of seconds: '))
str_tm = str(datetime.timedelta(seconds=sec))
day = str_tm.split(',')[0]
hour, minute, second = str_tm.split(',')[1].split(':')
print(f'{day}{hour} hour {minute} min {second} sec')

输出:

Enter the number of seconds: 176400
2 days 1 hour 00 min 00 sec

您似乎在尝试执行以下操作:

result = "time in minutes is"
if days >0:
    result += f" {days} days"
if hours > 0:
    result += f" {hours} hours"
if mins > 0:
    result += f" {mins} minutes"
if secs > 0:
    result += f" {secs} seconds"

您可以 assemble 列表中的非零部分并在最后加入它。您也可以使用 divmod 函数提取天、小时、分钟和秒:

sec = int(input("Enter time in Seconds: "))

time  = []
days,sec = divmod(sec,86400) # sec will get seconds in partial day
if days:
    time.append(f"{days} day"+"s"*(days>1))
    
hours,sec = divmod(sec,3600) # sec will get seconds in partial hour
if hours:
    time.append(f"{hours} hour"+"s"*(hours>1))
    
minutes,sec = divmod(sec,60) # sec will get seconds in partial minute
if minutes:
    time.append(f"{minutes} minute"+"s"*(minutes>1))
    
if sec:
    time.append(f"{sec} second"+"s"*(sec>1))

样本运行:

Enter time in Seconds: 176400
time is: 2 days, 1 hour

Enter time in Seconds: 1767671
time is: 20 days, 11 hours, 1 minute, 11 seconds

Enter time in Seconds: 259321
time is: 3 days, 2 minutes, 1 second

可以使用遍历除数和时间单位的循环来简化整个过程:

sec = int(input("Enter time in Seconds: "))

time  = []
for d,u in [(86400,"day"),(3600,"hour"),(60,"minute"),(1,"second")]:
    n,sec = divmod(sec,d)
    if n: time.append(f"{n} {u}"+"s"*(n>1))
    
print("time is:",", ".join(time))

就个人而言,我更喜欢使用更熟悉的值(例如一小时中的 60 分钟),这会稍微改变顺序。此外,时间字符串可以直接 assembled 而不是使用列表并在末尾加入:

sec = int(input("Enter time in Seconds: "))

time  = ""
for d,u in [(60,"second"),(60,"minute"),(24,"hour"),(sec,"day")]:
    sec,n = divmod(sec,d)
    if n: time = f"{n} {u}" + "s"*(n>1) + ", "*bool(time) + time
    
print("time is:",time)