40 lines
1.1 KiB
Python
40 lines
1.1 KiB
Python
![]() |
import re
|
||
|
|
||
|
time_regex = re.compile(r'(\d+)\s*([smhd]|seconds?|minutes?|hours?|days?)')
|
||
|
|
||
|
|
||
|
def parse_time(time_str):
|
||
|
"""
|
||
|
Parse time strings like "4m2s", "1h30m" into seconds.
|
||
|
|
||
|
Args:
|
||
|
time_str: String in format like "4m2s", "1h30m", "15m"
|
||
|
|
||
|
Returns:
|
||
|
Integer of total seconds or None if invalid
|
||
|
"""
|
||
|
units = {
|
||
|
'second': 1, 'seconds': 1, 's': 1,
|
||
|
'minute': 60, 'minutes': 60, 'm': 60,
|
||
|
'hour': 3600, 'hours': 3600, 'h': 3600,
|
||
|
'day': 86400, 'days': 86400, 'd': 86400,
|
||
|
'week': 604800, 'weeks': 604800, 'w': 604800
|
||
|
}
|
||
|
|
||
|
try:
|
||
|
matches = time_regex.findall(time_str)
|
||
|
if not matches:
|
||
|
return None
|
||
|
|
||
|
total_seconds = 0
|
||
|
for amount, unit in matches:
|
||
|
if unit not in units and len(unit) > 0:
|
||
|
unit = unit[0]
|
||
|
|
||
|
multiplier = units.get(unit.lower(), 1)
|
||
|
total_seconds += int(amount) * multiplier
|
||
|
|
||
|
return total_seconds if total_seconds > 0 else None
|
||
|
except Exception as e:
|
||
|
print(f"Time parsing error: {e}")
|
||
|
return None
|