Skip to content

Instantly share code, notes, and snippets.

@kasbah
Last active August 29, 2015 14:16
Show Gist options
  • Select an option

  • Save kasbah/8c70e4b2b99089ebe286 to your computer and use it in GitHub Desktop.

Select an option

Save kasbah/8c70e4b2b99089ebe286 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# total up time_sheet in tab seperated values of the format:
# START\tTue Dec 30 12:20:34 GMT 2014
# STOP\tTue Dec 30 14:59:46 GMT 2014
# ...
from __future__ import print_function
from datetime import datetime, timedelta, date
import sys
DATE_FORMAT_STRING = "%a %b %d %H:%M:%S %Z %Y"
with open("time_sheet.tsv", 'r') as infile:
just_today = False
just_yesterday = False
if len(sys.argv) > 1:
just_today = "today" in sys.argv or "t" in sys.argv
just_yesterday = "yesterday" in sys.argv or "y" in sys.argv
today = date.today().isocalendar()
yesterday = (date.today() - timedelta(1)).isocalendar()
total = timedelta()
line_no = 1
while True:
line1 = infile.readline()
line2 = infile.readline()
if not line2: break # EOF
s = line1.strip().split("\t")
if s[0] != "START":
print("Error on line " + str(line_no) + ". Expecting START, got:", s[0])
sys.exit(1)
start_time = datetime.strptime(s[1], DATE_FORMAT_STRING)
c = just_today and start_time.isocalendar() == today
c |= just_yesterday and start_time.isocalendar() == yesterday
c |= not just_today and not just_yesterday
if c:
s = line2.strip().split("\t")
if s[0] != "STOP":
print("Error on line "
+ str(line_no + 1)
+ ". Expecting STOP, got:", s[0])
sys.exit(1)
stop_time = datetime.strptime(s[1], DATE_FORMAT_STRING)
total += stop_time - start_time
line_no += 2
total_hours = (total.days * 24) + (total.seconds // 3600)
total_minutes = (total.seconds // 60) % 60
if total_hours == 1:
total_hours = str(total_hours) + " hour,"
else:
total_hours = str(total_hours) + " hours,"
if total_minutes == 1:
total_minutes = str(total_minutes) + " minute"
else:
total_minutes = str(total_minutes) + " minutes"
print(total_hours, total_minutes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment