【问题标题】:Converting seconds into days, hours, minutes & seconds in Python [closed]在 Python 中将秒转换为天、小时、分钟和秒 [关闭]
【发布时间】:2023-03-10 00:55:01
【问题描述】:

我有一个函数可以将秒返回天、小时、分钟和秒。但我需要但是,如果输出为 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”语句,但有更短的方法吗?

【问题讨论】:

  • 试着更清楚地思考你的预期逻辑。你可能会发现拿一支真正的铅笔和一张纸,然后画一个流程图很有帮助。也就是说,关于以更短或更“更优雅”的方式做事的问题通常不在此处讨论。如果代码已经正常工作,您可能想尝试codereview.stackexchange.com
  • 题外话,但您可以使用divmod() 来简化数学运算,例如day, sec = divmod(sec, 86400)

标签: python datetime converters


【解决方案1】:

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

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"

【讨论】:

    【解决方案2】:

    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
    

    【讨论】:

      【解决方案3】:

      您可以将非零部分组装在一个列表中并在最后加入。您还可以使用 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 分钟),这会稍微改变顺序。此外,时间字符串可以直接组装,而不是使用列表并在末尾加入:

      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)
      

      【讨论】:

        猜你喜欢
        • 2016-06-29
        • 2012-01-06
        • 2016-07-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多