pythontaskwarrior

how to display calculated timedelta as time in python


I'm calculating time stored in timewarrior via timew-report python library.

I'm adding up the time, which I'm able to do. And I'm trying get the total to display in just a number of hours:minutes:seconds, without days.

My script....

#!/usr/bin/python
import sys
import datetime
from datetime import timedelta
from timewreport.parser import TimeWarriorParser #https://github.com/lauft/timew-report

parser = TimeWarriorParser(sys.stdin)

total = datetime.datetime(1, 1, 1, 0, 0)
for interval in parser.get_intervals():
    duration = interval.get_duration()
    print(duration)
    total = total + duration
print(total)

...works properly, returning:

0:01:09
0:06:03
7:00:00
0:12:52
20:00:00
0001-01-02 03:20:04

...but instead of showing 0001-01-02 03:20:04 I'd like it to say 27:20:04.

How do I get it to be formatted like that?

Am I taking the wrong approach by initializing total like datetime.datetime(1, 1, 1, 0, 0)?


Solution

  • On the assumption that interval.get_duration is returning a datetime.timedelta object each time, you can just add these to an existing datetime.timedelta object, and then do the arithmetic to convert to HH:MM:SS format at the end. (You will need to do your own arithmetic because the default string representation for timedelta will use days and HH:MM:SS if the value exceeds 24 hours, which you don't want.)

    For example:

    import datetime
    
    total = datetime.timedelta(0)
    for interval in parser.get_intervals():
        duration = interval.get_duration()
        total += duration
    
    total_secs = int(total.total_seconds())
    secs = total_secs % 60
    mins = (total_secs // 60) % 60
    hours = (total_secs // 3600)
    
    print("{hours}:{mins:02}:{secs:02}".format(hours=hours, mins=mins, secs=secs))