Python函数将秒转换为分钟、小时和天

2024-04-22 16:37:36 发布

您现在位置:Python中文网/ 问答频道 /正文

问题: 编写一个程序,要求用户输入秒数,并按如下方式工作:

  • 一分钟有60秒。如果用户输入的秒数大于或等于60,则程序应显示该秒数中的分钟数。

  • 一小时有3600秒。如果用户输入的秒数大于或等于3600,则程序应显示该秒数中的小时数。

  • 一天有86400秒。如果用户输入的秒数大于或等于86400,则程序应显示该秒数中的天数。

到目前为止我所拥有的:

def time():
    sec = int( input ('Enter the number of seconds:'.strip())
    if sec <= 60:
        minutes = sec // 60
        print('The number of minutes is {0:.2f}'.format(minutes)) 
    if sec (<= 3600):
        hours = sec // 3600
        print('The number of minutes is {0:.2f}'.format(hours))
    if sec <= 86400:
        days = sec // 86400
        print('The number of minutes is {0:.2f}'.format(days))
    return

Tags: ofthe用户程序formatnumberifis
3条回答

这个tidbit对于显示不同粒度的运行时间非常有用。

我个人认为,效率问题在这里实际上毫无意义,只要没有做一些非常低效的事情。过早的优化是很多罪恶的根源。这足够快了,永远不会成为你的瓶颈。

intervals = (
    ('weeks', 604800),  # 60 * 60 * 24 * 7
    ('days', 86400),    # 60 * 60 * 24
    ('hours', 3600),    # 60 * 60
    ('minutes', 60),
    ('seconds', 1),
    )

def display_time(seconds, granularity=2):
    result = []

    for name, count in intervals:
        value = seconds // count
        if value:
            seconds -= value * count
            if value == 1:
                name = name.rstrip('s')
            result.append("{} {}".format(value, name))
    return ', '.join(result[:granularity])

…这提供了不错的输出:

In [52]: display_time(1934815)
Out[52]: '3 weeks, 1 day'

In [53]: display_time(1934815, 4)
Out[53]: '3 weeks, 1 day, 9 hours, 26 minutes'

要将秒(作为字符串)转换为日期时间,这也有帮助。你得到的天数和秒数。秒可以进一步转换为分钟和小时。

from datetime import datetime, timedelta
sec = timedelta(seconds=(input('Enter the number of seconds: ')))
time = str(sec)

这将把n秒转换为d天、h小时、m分钟和s秒。

from datetime import datetime, timedelta

def GetTime():
    sec = timedelta(seconds=int(input('Enter the number of seconds: ')))
    d = datetime(1,1,1) + sec

    print("DAYS:HOURS:MIN:SEC")
    print("%d:%d:%d:%d" % (d.day-1, d.hour, d.minute, d.second))

相关问题 更多 >