-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathconvtime.py
More file actions
41 lines (29 loc) · 1.1 KB
/
Copy pathconvtime.py
File metadata and controls
41 lines (29 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
"Module to convert configuration time values"
from __future__ import annotations
import sys
from datetime import timedelta
def todelta(time_str: str | float) -> timedelta:
'Convert time "nn[.d][smdhw]" string to timedelta'
# Ensure passed value is string
timestr = str(time_str).lower()
# Default is secs if no extension
if not timestr[-1].isalpha():
timestr += 's'
nums = timestr[:-1]
# Can accept float or int
if nums.replace('.', '', 1).isdigit():
num = float(nums) if '.' in nums else int(nums)
if timestr.endswith('s'):
return timedelta(seconds=num)
elif timestr.endswith('m'):
return timedelta(minutes=num)
elif timestr.endswith('h'):
return timedelta(hours=num)
elif timestr.endswith('d'):
return timedelta(days=num)
elif timestr.endswith('w'):
return timedelta(weeks=num)
sys.exit(f'Do not understand "{time_str}" time format')
def tosec(time_str: str) -> float:
'Convert time "nn[.d][smdhw]" string to secs'
return todelta(time_str).total_seconds()