Skip to content

Instantly share code, notes, and snippets.

@robballou
Created June 20, 2012 21:47
Show Gist options
  • Save robballou/2962435 to your computer and use it in GitHub Desktop.
Save robballou/2962435 to your computer and use it in GitHub Desktop.
Calculate the hours from the start of the work day
#!/usr/bin/env python
"""
workTime.py
Coded by: Rob Ballou ([email protected])
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
"""
import datetime, sys, re, argparse
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")
args = parser.parse_args()
print "%.2f hours" % round(get_work_time(args.start_time, args.lunch), 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment