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


>>> time24hr('12:34am')
    >>> time24hr('12:15pm')

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',
	pm = {'12':'12','1':'13','2':'14','3':'15','4':'16','5':'17','6':'18',
	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.

5 Years
Discussion Span
Last Post by Abhinav_4

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


Edited by ihatehippies: n/a

Votes + Comments
Good stuff.

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).

Votes + Comments
I have got to learn RedEx, as that looks like Chinese to me.

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.

Edited by pyTony: n/a


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'
            return "ERROR in " + tstr

Edited by woooee: n/a


This should be the simplest!

def time12to24hr(t):

    # Split into hour and minute with AM or PM
    [h,m] = input().strip().split(':')

    # m[-2:] because last two letters in minute are AM or PM
    if upper(m[-2:]) == 'AM':
        h = '00' if int(h)==12 else h

    # m[-2:] because last two letters in minute are AM or PM
    if upper(m[-2:]) == 'PM':
        h = '12' if int(h)==12 else int(h)+12

    return ('{0}{1}hr'.format(h, m[:-2]))
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.