Python 拆分持续时间字符串的函数

Python function to split up a duration string

全部!我正在制作一个 Discord 机器人,使用 ban 命令,可以在指定时间内禁止某人。持续时间字符串最多可达数天。完整的字符串可能如下所示:
1d / 5h30m / 14d / 10m
我正在寻找一种方法来解析这些字符串并得到像 {"minutes": 10, "hours": 5}
这样的东西它不需要是一个字典,只是我可以告诉它是哪个时间单位并相乘的东西以获得禁令应持续多长时间。 任何想法表示赞赏!

您可以使用正则表达式解析时间字符串,并使用datetime转换为所需的度量单位,例如秒数:

import re, datetime

test_str = '0d20h30m'

conv_dict = {
    'd': 'days',
    'h': 'hours',
    'm': 'minutes',
    's': 'seconds',
}

pat = r'[0-9]+[s|m|h|d]{1}'
def timestr_to_dict(tstr):
  'e.g. convert 1d2h3m4s to {"d": 1, "h": 2, "m": 3, "s": 4}'
  return {conv_dict[p[-1]]: int(p[:-1]) for p in re.findall(pat, test_str)}

print(timestr_to_dict(test_str))
{'days': 0, 'hours': 20, 'minutes': 30}

def timestr_to_seconds(tstr):
  return datetime.timedelta(**timestr_to_dict(tstr)).total_seconds()

print(timestr_to_seconds(test_str))
# 73800.0

我找到了这个名为 durations 的软件包(可以从 pip 安装),它完全可以满足您的需求。 (不要将它与 duration 混淆)。

来自他们的自述示例:

>>> from durations import Duration

>>> one_hour = '1hour'

>>> one_hour_duration = Duration(one_hour)
>>> one_hour_duration.to_seconds()
3600.0
>>> one_hour_duration.to_minutes()
60.0


# You can even compose durations in their short
# and long variations
>>> two_days_three_hours = '2 days, 3h'
>>> two_days_three_hours_duration = Duration(two_days_three_hours)
>>> two_days_three_hours_duration.to_seconds()
183600.0
>>> two_days_three_hours_duration.to_hours()
51.0