33 lines
1.2 KiB
Python
33 lines
1.2 KiB
Python
|
import datetime
|
||
|
import re
|
||
|
|
||
|
def parse_time(time_str):
|
||
|
# Parse the time string and return a timedelta
|
||
|
try:
|
||
|
time_components = re.findall(r'(\d+)\s*([dDhHrRmMsS]?)', time_str)
|
||
|
total_seconds = 0
|
||
|
for value, unit in time_components:
|
||
|
value = int(value)
|
||
|
if unit.lower() in ('d', 'day', 'days'):
|
||
|
total_seconds += value * 86400 # seconds in a day
|
||
|
elif unit.lower() in ('h', 'hr', 'hour', 'hours'):
|
||
|
total_seconds += value * 3600 # seconds in an hour
|
||
|
elif unit.lower() in ('m', 'min', 'minute', 'minutes'):
|
||
|
total_seconds += value * 60 # seconds in a minute
|
||
|
elif unit.lower() in ('s', 'sec', 'second', 'seconds'):
|
||
|
total_seconds += value
|
||
|
return datetime.timedelta(seconds=total_seconds)
|
||
|
except ValueError:
|
||
|
return None
|
||
|
|
||
|
if __name__ == '__main__':
|
||
|
print(parse_time('1d 2h 3m 4s'))
|
||
|
print(parse_time('1d2h3m4s'))
|
||
|
print(parse_time('1d 2h 3m'))
|
||
|
print(parse_time('1d 2h'))
|
||
|
print(parse_time('1d'))
|
||
|
print(parse_time('1h 2m 3s'))
|
||
|
print(parse_time('1h 2m'))
|
||
|
print(parse_time('1h'))
|
||
|
print(parse_time('1m 2s'))
|
||
|
print(parse_time('1m'))
|