1

I want to write a simple timesheet script. My input file looks like

9:00 17:00
10:45 12:35
11:00 15:00

I would like to read it in, compute the number of hours worked per day and then sum those hours up. When the day started before 12:00 and ended after 13:00 I would like to subtract half an hour too for lunch break.

My attempt so far is:

import sys
from datetime import datetime

gap = datetime.strptime('00:30','%H:%M')
hours = []
for line in sys.stdin:
    (start_time,end_time) = line.split()
    start_time = datetime.strptime(start_time, '%H:%M')
    end_time = datetime.strptime(end_time, '%H:%M')
    #if start_time before 12:00 and end_time after 13:00 then subtract gap
    hours.append(end_time-start_time)       
print sum(hours)

I don't know how to get the if statement line to work and summing the hours doesn't seem to work either as you can't sum datetime.timedelta types.


Thanks to the link in the comments, replacing sum(hours) with reduce(operator.add, hours) works.

The remaining part is how to test if start_time is before 12:00 and end_time is after 13:00 and if so to reduce the timedelta by half an hour.

Simd
  • 19,447
  • 42
  • 136
  • 271
  • 3
    Take a look: http://stackoverflow.com/questions/13897246/python-time-subtraction – Fusseldieb Oct 18 '16 at 11:24
  • And here: http://stackoverflow.com/questions/3096953/difference-between-two-time-intervals-in-python – Fusseldieb Oct 18 '16 at 11:25
  • @Fusseldieb I looked at your links thank you. It seems reduce(operator.add, hours) is how you add the hours. How do you do the if statement and the gap subtraction. – Simd Oct 18 '16 at 11:31

1 Answers1

2

You are using incorrect code (and syntax) in your if statement.

if start_time < datetime.strptime('12:00', '%H:%M') and end_time > datetime.strptime('13:00', '%H:%M'):
    delta_hours = end_time.hour - start_time.hour)
    delta_minutes = end_time.minutes - start_time.minutes)
    # Do whatever your want with it now.
    # Substraction of the break is not implemented in this example, it depends on how you want to save it.

Time delta might be worth looking into as well, it can use basic operations like

a = timedelta(...)
b = timedelta(...)
c = b - a - gap
vriesdemichael
  • 914
  • 1
  • 7
  • 19