Skip to main content

Python: Timesheet Calculator

Little programs are so much fun to write ;) Here's one that adds up the hours in my time sheet.
#!/usr/bin/env python

"""Add up the hours in my hours.otl file.

The file should have the following format::

12/21/2008
3.25 hours working on project-specific domain names.

The date must be in margin 0. The number of hours must be indented.

Testing::

nosetests --with-doctest addhours.py

Note, I'm positive that this script could be replaced by a one line
awk script, but whatever. It was fun to write.

"""

from cStringIO import StringIO
from optparse import OptionParser
import re
import sys

TEST_DATA = """\
12/18/2008
7 Hours programming.

12/19/2008
8 Hours hacking.
"""

hours_regex = re.compile(r"^\s+([0-9.]+)")

__docformat__ = "restructuredtext"


def process_file(f):
"""Add up and return the hours in the given open file handle.

This may raise a ValueError if the file is malformed.

Test::

>>> process_file(StringIO(TEST_DATA))
15.0

"""
total = 0
for line in f:
match = hours_regex.match(line)
if match is not None:
total += float(match.group(1))
return total


def main():
"""Run the program.

Deal with optparse, printing nice error messages, etc.

"""
parser = OptionParser("usage: %prog < hours.otl")
(options, args) = parser.parse_args()
if args:
parser.error("No arguments expected")
try:
print process_file(sys.stdin)
except ValueError, e:
parser.error("Malformed file: %s" % e)


if __name__ == '__main__':
main()

Comments