Skip to content

Instantly share code, notes, and snippets.

@puppe
Created January 20, 2013 11:31
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 puppe/4578030 to your computer and use it in GitHub Desktop.
Save puppe/4578030 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
#
# Given time-tracking data in the following CSV format
#
# Date,Begin,End,Comments
# 18.01.2013,9:00,13:00,done this
# 18.01.2013,14:00,17:00,"done that, and also that other thing"
# 12.12.2012,12:00,12:12,
#
# timetracking.py reads this data from stdin and computes total times
# per month and overall. The results are presented like this
#
# 2012/12: 0:12
# 2013/01: 7:00
# total: 7:12
#
# Limitations:
#
# * Obviously begin and end of every record must be on the same day.
# * Daylight saving is not taken into account.
import sys
import csv
from datetime import datetime
from datetime import timedelta
def delta_to_hm(delta):
days, seconds = delta.days, delta.seconds
hours = days * 24 + seconds // 3600
minutes = (seconds // 60) % 60
return hours, minutes
reader = csv.reader(sys.stdin)
next(reader) # Ignore first line
delta_sums = dict()
for row in reader:
begin = datetime.strptime(row[0] + row[1], '%d.%m.%Y%H:%M')
end = datetime.strptime(row[0] + row[2], '%d.%m.%Y%H:%M')
delta = end - begin
month = begin.year, begin.month
delta_sums[month] = delta_sums.get(month, timedelta()) + delta
total = timedelta()
for month in sorted(delta_sums.keys()):
delta = delta_sums[month]
total = total + delta
hours, minutes = delta_to_hm(delta)
print('{}/{:02}: {:4}:{:02}'.format(month[0], month[1], hours, minutes))
total_hours, total_minutes = delta_to_hm(total)
print('total: {:4}:{:02}'.format(total_hours, total_minutes))
# vim: set ts=4 sw=4 sts=4 tw=72 et :
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment