view timedelta.py @ 1:5fa902852779 default tip

add unit tests for timedelta function
author Dirk Olmes <dirk@xanthippe.ping.de>
date Sat, 10 Jan 2009 04:09:22 +0100
parents 78a59d65bfcc
children
line wrap: on
line source


from datetime import time

def __toMicroseconds(time):
    result = time.microsecond
    result += time.second * 1000000
    result += time.minute * 60 * 1000000
    result += time.hour * 60 * 60 * 1000000
    return result

def timedelta(t1, t2):
    """Calculate the difference between to datetime.time objects
    
    The result is returned as a time object as the datetime.timedelta does not provide
    the same timeunits (hour, minute etc.) as the time objects that come as input to 
    this routine.
    
    This method always returns a positive difference, i.e. the order in which the two
    time objects are passed does not matter.
    """
    min = t1
    max = t2
    if t2 < t1:
        min = t2
        max = t1
    
    total1 = __toMicroseconds(min)
    total2 = __toMicroseconds(max)
    
    difference = total2 - total1
    
    hours = ((difference / 1000000) / 60) / 60
    difference -= hours * 60 * 60 * 1000000
    
    minutes = (difference / 1000000) / 60
    difference -= minutes * 60 * 1000000
    
    seconds = difference / 1000000
    difference -= seconds* 1000000
    
    micro = difference 
    return time(hour=hours, minute=minutes, second=seconds, microsecond=micro)