Skip to content

Instantly share code, notes, and snippets.

@harrybiddle
Last active October 12, 2017 14:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harrybiddle/a839a3492aef1a37d0447cabfc52f549 to your computer and use it in GitHub Desktop.
Save harrybiddle/a839a3492aef1a37d0447cabfc52f549 to your computer and use it in GitHub Desktop.
Simple Python script for computing differences between times
#! /usr/bin/env python3
import argparse
import sys
from dateutil import parser as date_parser
from datetime import datetime
INTERVALS = (('years', 60 * 60 * 24 * 7 * 52),
('weeks', 60 * 60 * 24 * 7),
('days', 60 * 60 * 24),
('hours', 60 * 60),
('minutes', 60),
('seconds', 1))
def pretty_print_seconds(seconds):
result = []
for name, count in INTERVALS:
value = seconds // count
if value:
seconds -= value * count
if value == 1:
name = name.rstrip('s')
result.append('{} {}'.format(value, name))
return ', '.join(result)
def main(argv):
parser = argparse.ArgumentParser(description=('Enter any two times. If the '
'second argument is ommitted, it is assumed to be the current time'))
parser.add_argument('t1')
parser.add_argument('t2', nargs='?')
args = parser.parse_args(argv[1:])
t1 = date_parser.parse(args.t1)
if args.t2 is not None:
t2 = date_parser.parse(args.t2)
else:
t2 = datetime.now()
diff = (t2 - t1)
print (pretty_print_seconds(int(diff.total_seconds())))
if __name__ == '__main__':
sys.exit(main(sys.argv))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment