Problem Statement
You are given time in AM/PM format. Convert this into a 24 hour format.
Note Midnight is \$ 12:00:00AM \$ or \$ 00:00:00 \$ and 12 Noon is \$ 12:00:00PM. \$
Input Format
Input consists of time in the AM/PM format i.e. hh:mm:ssAM or hh:mm:ssPM where \$ 01 \le hh \le 12 \$, \$ 00 \le mm \le 59 \$, \$ 00 \le ss \le 59 \$
Output Format
You need to print the time in 24 hour format i.e. hh:mm:ss where
\$ 00 \le hh \le 23 \$, \$ 00 \le mm \le 59 \$, \$ 00 \le ss \le 59 \$
Sample Input
\$ 07:05:45PM \$
Sample Output
\$ 19:05:45 \$
Solution
class AbsTime(object):
def __init__(self, hh, mm=0, ss=0, pm=False):
self.hh = hh
self.mm = mm
self.ss = ss
self.pm = pm
def add(self, time):
self.hh += time.hh
self.mm += time.mm
self.ss += time.ss
if self.ss >= 60:
self.ss -= 1
self.mm += 1
if self.mm >= 60:
self.mm -= 1
self.hh = self.hh % 24
return self
def midnight(self):
return not self.pm and str(self) in ['00:00:00', '12:00:00']
def noon(self):
return self.pm and str(self) == '12:00:00'
def __str__(self):
return "{0:02d}:{1:02d}:{2:02d}".format(self.hh, self.mm, self.ss)
def get(self):
if self.midnight():
return AbsTime(0)
if self.noon():
return AbsTime(12)
if self.pm:
if self.hh == 12:
hh = self.hh
else:
hh = self.hh + 12
return AbsTime(hh, self.mm, self.ss)
else:
return AbsTime(self.hh % 12, self.mm, self.ss)
@classmethod
def create_from_string(cls, time):
pm = True if time[-2:] == 'PM' else False
hh, mm, ss = map(int, time[:-2].split(':'))
return cls(hh, mm, ss, pm)
def main(time):
if time == '00:00:00':
return time
abstime = AbsTime.create_from_string(time)
return abstime.get()
if __name__ == '__main__':
TIME = raw_input().strip()
print main(TIME)
#print main('00:00:00') #00:00:00
#print main('12:00:00PM') #12:00:00
#print main('12:00:00AM') #00:00:00
#print main('02:00:00PM') #14:00:00
#print main('02:00:00AM') #02:00:00
#print main('11:59:00AM') #11:59:00
#print main('12:59:00PM') #12:59:00
#print main('01:00:00PM') #13:00:00
#print main('11:59:59PM') #23:59:59
#print main('12:59:59AM') #00:59:59
It really took me a while to do this simple solution, its fast when we do just structural programming but once I thought to step into OOP world things really got confusing. How can I improve this design?