繁体   English   中英

Python | 将秒变成天、月、小时的问题

[英]Python | Issue with turning seconds into days, months, hours

我正在为我的 Discord 机器人制作一个赠品命令,我想将秒转换为天、月 + 小时这是我的代码:

try:
            duration = time.split('d')[0] * 86400
        except IndexError:
            try:
                duration = time.split('h')[0] * 3600
            except IndexError:
                try:
                    duration = time.split('m')[0] * 60
                except IndexError:
                    pass
        print(duration)

忽略缩进,它们在 VS Code 中是正常的。 “时间”被定义为“1m”,然后我将“m”拆分为“1”,它至少打印了很多次“1m”这样的持续时间。 我输入定义为“时间”的持续时间,例如“2d”,我希望以秒为单位,即 172800 秒。

它不起作用,因为str.split返回整个字符串是没有拆分字符:

>>> print('aaa'.split('b'))
['aaa']
>>> _

我会以更短、更明确的方式来做。

import re

SECONDS_IN = {  # Number of seconds per suffix.
  'm': 60,  # minute.
  'h': 3600,  # hour.
  'd': 86400,  # day.
}

def time_in_sec(s):
  # Split by either m, d, or h.
  pieces = re.split('(m|d|h)', s)
  if len(pieces) < 2:  # Did not split.
    raise ValueError('%r is not a valid time string' % s)
  amount = pieces[0]  # The number.
  suffix = pieces[1]  # The m, d, or h.
  return int(amount) * SECONDS_IN[suffix]

现在您可以尝试:

for s in ['5m', '2h', '1d', '100k']:
  print(s, '=', time_in_sec(s), 'seconds')

5m = 300 seconds
2h = 7200 seconds
1d = 86400 seconds
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in time_in_sec
ValueError: '100k' is not a valid time string

当然,这离强大的解析器还很远。 如果您想以稳健的方式处理输入,请考虑使用类似arrow的库。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM