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.

Recommended Answers

All 5 Replies

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

commented: Good stuff. +1

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

commented: I have got to learn RedEx, as that looks like Chinese to me. +1

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.

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

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]))
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.