Skip to content

Instantly share code, notes, and snippets.

@frennkie
Last active Aug 23, 2017
Embed
What would you like to do?
#!/usr/bin/env python3
import datetime
import argparse
import re
DT_NOW = datetime.datetime.now()
def mkdate(datestring):
if isinstance(datestring, datetime.datetime):
return datestring
try:
return datetime.datetime.strptime(datestring, '%Y-%m-%dT%H:%M')
except ValueError:
return datetime.datetime.strptime(datestring, '%Y-%m-%d')
# https://gist.github.com/jnothman/4057689
_units = dict(W=7*60*60*24, w=7*60*60*24,
D=60*60*24, d=60*60*24,
H=60*60, h=60*60,
M=60, m=60,
S=1, s=1)
def mkdelta(deltavalue):
seconds = 0
defaultunit = unit = _units['d'] # default to days
value = ''
for ch in list(str(deltavalue).strip()):
if ch.isdigit():
value += ch
continue
if ch in _units:
unit = _units[ch]
if value:
seconds += unit * int(value)
value = ''
unit = defaultunit
continue
if ch in ' \t':
# skip whitespace
continue
raise ValueError('Invalid time delta: %s' % deltavalue)
if value:
seconds = unit * int(value)
return datetime.timedelta(seconds=seconds)
parser = argparse.ArgumentParser()
parser.add_argument('--start',
type=mkdate,
help="start date(time) - ISO format e.g. 2016-11-23 or 2016-12-24T14:50")
parser.add_argument('--end',
type=mkdate,
help="end date(time) - ISO format e.g. 2016-11-23 or 2016-12-24T14:50")
parser.add_argument('--delta',
type=mkdelta,
help="delta (time delta) - e.g. 1w5d6h7m8s")
args = parser.parse_args()
if args.delta:
if args.start and args.end: # all three options set
raise Exception("too many arguments provided - specfiy either:\n"
"1) DELTA (e.g. --days 1) or\n"
"2) START (e.g --start 2016-12-24T14:50) or\n"
"3) START and END (e.g. --start 2016-01-01 --end 2016-01-31 )")
elif args.start: # start and delta set
raise Exception("invalid argument combination (START and DELTA) - specfiy either:\n"
"1) DELTA (e.g. --delta 1w5d) or\n"
"2) START (e.g --start 2016-12-24T14:50) or\n"
"3) START and END (e.g. --start 2016-01-01 --end 2016-01-31 )")
else: # delta and end (use now if end is not set)
if not args.end:
dt_end = DT_NOW
else:
dt_end = args.end
dt_start = dt_end - args.delta
else:
if args.start and args.end: # start and end given
dt_start = args.start
dt_end = args.end
elif args.start and not args.end: # start give (use now for end)
dt_start = args.start
dt_end = DT_NOW
else:
raise Exception("too few arguments provided - specfiy either:\n"
"1) DELTA (e.g. --delta 1w5d) or\n"
"2) START (e.g --start 2016-12-24T14:50) or\n"
"3) START and END (e.g. --start 2016-01-01 --end 2016-01-31 )")
if dt_start > dt_end:
raise Exception("START has to be an earlier date than END")
print("startT: {}".format(type(dt_start)))
print("start: {}".format(dt_start))
print("endT: {}".format(type(dt_end)))
print("end: {}".format(dt_end))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment