Yes, yes, and yes. Welcome to the freedom of Python. :)
First of all, as is typical for Python, there is a module called time (and another one, datetime) that does exactly this stuff automagically. Look them up in the Python docs.
But if you wanted to do it by hand, it might go like this:
def parsetime(timestr):
if timestr.endswith("PM"):
offset = 12
timestr = timestr[:-2] # strip off 'PM'
elif timestr.endswith("AM"):
offset = 0
timestr = timestr[:-2]
else: # assume military time
offset = 0
if ":" in timestr:
hr, minute = timestr.split(":")
if hr == "12":
hr = "0"
else: # military time
minute = timestr[-2:]
hr = timestr[:-2]
return int(hr) + int(minute)/60. + offset
def printtime(time, military=False):
time = time % 24
if military:
hr = "00%d" % (int(time))
minute = "00%d" % (int((time % 1) * 60 + 0.5))
return hr[-2:]+minute[-2:]
else:
hr = "00%d" % (int(time) % 12)
if int(time) % 12 == 0:
hr = "12"
minute = "00%d" % (int((time % 1) * 60 + 0.5))
if int(time) > 11:
offset = "PM"
else:
offset = "AM"
return hr[-2:] + ":" + minute[-2:] + offset
These aren't perfect (as in, they allow illegal times), but they give an idea as well as showcasing some differences between Python and Java.
Jeff
jrcagle
Practically a Master Poster
608 posts since Jul 2006
Reputation Points: 92
Solved Threads: 156