954,515 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

function to convert from 12hr to 24 hr?

it says the following:
Write a function that converts the time to 24hr format.

Examples

>>> time24hr('12:34am')
    '0034hr'
    >>> time24hr('12:15pm')
    '1215hr'


so i wrote the following:

def time24hr(tstr):
	a = tstr.split(':')
	am = {'12':'00','1':'01','2':'02','3':'03','4':'04','5':'05','6':'06',
	      '7':'07','8':'08','9':'09','10':'10','11':'11'}
	pm = {'12':'12','1':'13','2':'14','3':'15','4':'16','5':'17','6':'18',
	      '7':'19','8':'20','9':'21','10':'22','11':'23'}
	if 'am' in tstr:
		return am[a[0]] + a[1][:2] + 'hr'
	elif 'pm' in tstr:
		return pm[a[0]] + a[1][:2] + 'hr'


But what would have been a better way to do it? i imagine their is an inbuilt method of doing this, but is there a more efficient way to do this without inbuilts?
and could you show any inbuilt ways too, would be much appreciated.

pwolf
Junior Poster in Training
71 posts since Dec 2011
Reputation Points: 10
Solved Threads: 0
 

look into time.strftime (string format time)

import time
time.strftime("%a %m/%d/%y @ %H:%M:%S", time.localtime())

returns 'Mon 01/23/12 @ 17:38:22'

if you only wanted the time portion just do

time.strftime("%H:%M:%S", time.localtime())


here is a reference for the meaning of each letter http://strftime.org/

ihatehippies
Junior Poster
190 posts since Oct 2008
Reputation Points: 33
Solved Threads: 13
 

If you need to write your own instead of using strftime/strptime, the right answer is probably regular expressions

Regular expression syntax is tricky if you don't already know it (and sometimes, if you do).

import re
timeS = r'(?P<hour>[01]?\d):(?P<minute>[0-5]\d) *((?P<am>[Aa]\.?[Mm].?)|(?P<pm>[Pp]\.?[Mm]\.?))
timeRE = re.compile(timeS)
# ... get somestring "some how"
m = timeRE.match(somestring)
# now look at m.groups, being careful to cope with failure modes

Beware that this regex will pass bad strings such as "19:18 pm" or "12:15 xx" and will not accept a valid time 24 hour time such as "22:23" (easy to fix in timeS if you want it).

griswolf
Veteran Poster
1,165 posts since Apr 2010
Reputation Points: 344
Solved Threads: 256
 

It is possible to make it one liner, but the dictionary approach is clearer or using few more if statements. Maybe you should anyway normalize the case of input to take both 'am' and 'AM' and accept hours with ' ' or '0' in front and also extra blanks at end of string.
Nicer way for me to build the return value is by string formatting

'%02i%02ihr' % (hr, m)


or by format method, if you use calculations with integers instead of lookup.

pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

Instead of the dictionary, which is fine, you can add 12 to the time if "PM" and less than 12. And another point that is picky for the example, but relevant in other things you might do, is to use endswith instead of in, to only catch AM of PM if they are at the end of the string.

t_lower = tstr.strip().lower()
	if t_lower.endswith("am"):
		return am[a[0]] + a[1][:2] + 'hr'
	elif t_lower.endswith("pm"):
		return pm[a[0]] + a[1][:2] + 'hr'
        else:
            return "ERROR in " + tstr
woooee
Nearly a Posting Maven
2,454 posts since Dec 2006
Reputation Points: 777
Solved Threads: 714
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: