Skip to content
This repository has been archived by the owner on Apr 22, 2020. It is now read-only.

raise error with invalid time spec #298

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions zmon_worker_monitor/builtins/plugins/time_.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,18 @@ def __init__(self, spec='now', utc=False):
if isinstance(spec, Number):
self.time = datetime.utcfromtimestamp(spec) if utc else datetime.fromtimestamp(spec)
else:
delta = parse_timedelta(spec)
if delta:
self.time = now + delta
elif spec == 'now':
if spec == 'now':
self.time = now
else:
self.time = parse_datetime(spec)
delta = None
try:
delta = parse_timedelta(spec)
except Exception:
pass
if delta:
self.time = now + delta
else:
self.time = parse_datetime(spec)

def __sub__(self, other):
'''
Expand Down
24 changes: 15 additions & 9 deletions zmon_worker_monitor/zmon_worker/common/time_.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,14 @@
def parse_timedelta(s):
'''
>>> parse_timedelta('bla')

Traceback (most recent call last):
...
ValueError: invalid literal for int() with base 10: 'bl'

>>> parse_timedelta('1k')

Traceback (most recent call last):
...
ValueError: invalid time unit: k

>>> parse_timedelta('1s').total_seconds()
1.0
Expand All @@ -42,21 +46,23 @@ def parse_timedelta(s):
factor = -1
else:
factor = 1
try:
v = int(s[:-1])
u = s[-1]
except Exception:
return None

v = int(s[:-1])
u = s[-1]

if u not in TIME_UNITS:
raise ValueError('invalid time unit: {}'.format(u))
arg = TIME_UNITS.get(u)
if arg:
return factor * timedelta(**{arg: v})
return None


def parse_datetime(s):
'''
>>> parse_datetime('foobar')
Traceback (most recent call last):
...
ValueError: invalid datetime foobar

>>> parse_datetime('1983-10-12T23:30').isoformat(' ')
'1983-10-12 23:30:00'
Expand Down Expand Up @@ -91,4 +97,4 @@ def parse_datetime(s):
return datetime.strptime(s, fmt) - timezone_timedelta
except Exception:
pass
return None
raise ValueError('invalid datetime {}'.format(s))