Source code for Time
class Time(object):
[docs] def __init__(self, h, m, s):
"""Store time internally as seconds """
self.sec = s + m*60 + h*60*60
[docs] def __str__(self):
""" Print time externally as military time """
h = self.sec/3600
m = (self.sec-(h*3600))/60
s = self.sec - h*3600 - m*60
return '%02d:%02d:%02d' %(h,m,s)
def convert(self):
""" Convert time to its input form """
h = self.sec/(3600)
m = (self.sec - h*3600)/60
s = self.sec - h*3600 - m*60
return (h,m,s)
def __add__(self, other):
""" Take in time object, add to self, return new time object
"""
(h,m,s) = self.convert()
newTime = Time(h,m,s)
newTime.sec += other.sec
if newTime.sec >= 86400:
newTime -= 86400
return newTime
def __sub__(self, other):
""" Time in time object, subtract from self, return new time object
"""
(h,m,s) = self.convert()
newTime = Time(h,m,s)
newTime.sec -= other.sec
if newTime.sec < 0:
newTime.sec = 0
return newTime
def am_or_pm(self):
""" Is Time before or after 12:00:00 """
if self.sec < 43200:
return "AM"
else:
return "PM"
if __name__ == "__main__":
time1 = Time(5,5,5)
time2 = Time(12,0,0)
print str(time1+time2)
print str(time2-time1)
print time2.am_or_pm()
print time1.am_or_pm()