Hamideh
Hamideh

Reputation: 13

How to add time durations?

I want to add time durations attributes in an xml file using Python 2.7.

import xml.etree.ElementTree as ET
import time

for k in root.findall('TC'):
    ttt= k.get('time')
    s = time.strptime(ttt, "%H:%M:%S")
    total_time = total_time + s

I can't use + operator, the error is unsupported operand types (+) None_Type, time.struct_time.

How can I define total_time as a struct_time?

Upvotes: 1

Views: 736

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123400

You'll need to convert the struct_time components to a datetime.timedelta object to sanely deal with time durations:

import datetime
import time

total_time = datetime.timedelta()
for k in root.findall('TC'):
    ttt= k.get('time')
    s = time.strptime(ttt, "%H:%M:%S")
    total_time = total_time + datetime.timedelta(
        hours=s.tm_hour, minutes=s.tm_minute, seconds=s.tm_second)

There is no easy way otherwise to convert the struct_time information to a duration; it is actually meant for date-time values, although using .strptime() to parse a duration is not too bad an idea.

Your total_time value is now a datetime.timedelta() object. To get the total number of seconds, use the .total_seconds() method on it:

print total_time.total_seconds()

Upvotes: 3

Related Questions