Skip to content

Instantly share code, notes, and snippets.

@robballou
Created February 23, 2017 19:02
Show Gist options
  • Save robballou/7b1c30412f186d95e29cb3b5b4aaebcb to your computer and use it in GitHub Desktop.
Save robballou/7b1c30412f186d95e29cb3b5b4aaebcb to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""
workTime.py
Coded by: Rob Ballou (rob@robballou.com)
Calculates the number of hours that have passed
in a work day (starting at 8:30).
The start time can be changed by passing the hour and min
as commandline arguments:
# get the worktime starting at 7
workTime.py 7
# get the worktime starting at 7:45
workTime.py 7 45
workTime.py 7:45
# output only the decimal representation
workTime.py --decimal-only 7
# output only the clock time representation
workTime.py --time-only 7
"""
import datetime, re, argparse, sys
def get_work_time(start_time, lunch=False):
"""
Figure out the work time from the specified start time
"""
time_pattern = re.compile('^(\d{1,2})[:\s]?(\d{1,2})?')
# if the argument is a list, join it into a time
start_time = ':'.join(start_time)
start_time = time_pattern.match(start_time)
if not start_time:
raise Exception("Invalid start time")
start_time = start_time.groups()
# get the hour/min
hour = int(start_time[0])
if start_time[1]:
minutes = int(start_time[1])
else:
minutes = 0
# if the lunch arg is set, we add an hour
if args.lunch:
hour += 1
# figure out the difference between now and then
now = datetime.datetime.today()
then = datetime.datetime(now.year, now.month, now.day, hour, minutes, 0, 0, None)
if then < now:
then = then + datetime.timedelta(days=1)
diff = now - then
diff = diff.seconds / (60.0 * 60.0)
return diff
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("start_time",
default="8:30",
nargs="*",
help="The start time for your work day. Examples: 8:30, 8, 7 30")
parser.add_argument("--lunch", '-l', action='store_true', default=False, help="Account for an hour lunch")
group = parser.add_mutually_exclusive_group()
group.add_argument('--decimal-only', '-d', action='store_true', default=False)
group.add_argument('--time-only', '-t', action='store_true', default=False)
args = parser.parse_args()
# print decimals
time = round(get_work_time(args.start_time, args.lunch), 2)
# print time
hours = int(time)
minutes = (time - hours) * 60
clock_time = "%d:%01d" % (hours, minutes)
if args.decimal_only:
print("%.2f" % time)
sys.exit()
if args.time_only:
print(clock_time)
sys.exit()
print("%.2f hours" % time)
print("%s hours" % clock_time)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment