Python函数来分割持续时间字符串

问题描述 投票:0回答:2

全部!我正在制作一个Discord机器人,并使用ban命令,将提供一种在特定时间内禁止某人的方法。持续时间字符串将长达几天。完整的字符串可能类似于以下内容:1d /5h30m/14d/10m我正在寻找一种解析这些字符串并获取诸如{"minutes": 10, "hours": 5}之类的东西的方法,它不必是字典,只需在其中我就可以知道它是哪个时间单位并乘以它以得到禁令多长时间应该持续。任何想法表示赞赏!

python discord.py text-parsing
2个回答
1
投票

您可以使用正则表达式解析时间字符串,并使用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

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
© www.soinside.com 2019 - 2024. All rights reserved.