python中方便的时间字符串解析

2024-05-01 21:30:58 发布

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

我需要计算elasticsearch索引清理从特定日期到现在的持续时间。 我的工作将在python中运行。 我有一个配置文件:

indices:
  - name: test
    template: raw*
    liveLength: 1d

如何将字符串“1d”或“2m”解析为有效的时间间隔,以便从liveLength字段中的特定日期计算持续时间?你知道吗


Tags: 字符串nametestraw间隔配置文件时间template
3条回答

我在GitHub上找到了代码:

from decimal import Decimal
from datetime import timedelta


def duration(duration_string): #example: '5d3h2m1s'
    duration_string = duration_string.lower()
    total_seconds = Decimal('0')
    prev_num = []
    for character in duration_string:
        if character.isalpha():
            if prev_num:
                num = Decimal(''.join(prev_num))
                if character == 'd':
                    total_seconds += num * 60 * 60 * 24
                elif character == 'h':
                    total_seconds += num * 60 * 60
                elif character == 'm':
                    total_seconds += num * 60
                elif character == 's':
                    total_seconds += num
                prev_num = []
        elif character.isnumeric() or character == '.':
            prev_num.append(character)
    return timedelta(seconds=float(total_seconds))

很好example

您可以使用正则表达式来提取数字/时间单位部分,然后在字典中查找乘法器。通过这种方式,它比your手动解析和if/elif链要短一些,而且可能可读性更高。你知道吗

>>> mult = {"s": 1, "m": 60, "h": 60*60, "d": 60*60*24}
>>> s = "2d 4h 13m 5.2s"
>>> re.findall(r"(\d+(?:\.\d)?)([smhd])", s)
[('2', 'd'), ('4', 'h'), ('3', 'm'), ('5.2', 's')]
>>> sum(float(x) * mult[m] for x, m in _)
187385.2

作为一个函数:

def duration(string):
    mult = {"s": 1, "m": 60, "h": 60*60, "d": 60*60*24}
    parts = re.findall(r"(\d+(?:\.\d)?)([smhd])", string)
    total_seconds = sum(float(x) * mult[m] for x, m in parts)
    return timedelta(seconds=total_seconds)

print(duration("2d 4h 13m 5.2s"))
# 2 days, 4:03:05.200000

这也将确保数字部分实际上是一个有效的数字(而不仅仅是任何数字和点的序列)。此外,如果使用了允许的时间单位以外的任何时间单位,它将引发异常。你知道吗

通过在函数外使用re.compile预编译regex,可以进一步优化函数。当我用IPython的%timeit测试它时,我的测试速度要快一点(2.1µs对你的测试速度是2.8µs,两者都没有timedelta创建,而且只使用float而不是Decimal)。另外,我认为这是一个更具可读性,有更多的声明性和更少的命令性风格,但这肯定是一个品味和偏好的问题。你知道吗

这是我的解决方案;我使用了python datetime库,它是timedelta

import datetime

intervals = {
    "w": datetime.timedelta(weeks=1),
    "d": datetime.timedelta(days=1),
    "h": datetime.timedelta(hours=1),
    "m": datetime.timedelta(minutes=1),
    "s": datetime.timedelta(seconds=1)
    }

def parse_live_length(string):
    time_interval_start_index = 0

    for char in string:
        if char.isnumeric():
            time_interval_start_index += 1
        else:
            return int(string[0:time_interval_start_index]), string[time_interval_start_index:]

    return False

# "2w" used as an example
live_length = "2w"
time_scalar, ll_interval = parse_live_length(live_length)

for interval in intervals:
    if interval == ll_interval:
        new_delta = time_scalar * intervals[interval]
        break 

# Example of how it could be used
current = datetime.datetime.now()
new_time = new_delta + current
print(new_time.day, new_time.month, new_time.year)

相关问题 更多 >