Converting a 24-hour time like "0830" or "2030" to a 12-hour time (like "8:30 am" or "8:30 pm") sounds easy enough, right?  Well, let's see if you can do it!

You will have to define a function named "to12hourtime", and you will be given a four digit time string (in "hhmm" format) as input.

Your task is to return a 12-hour time string in the form of "h:mm am" or "h:mm pm".  (Of course, the "h" part will be two digits if the hour is greater than 9.)

If you like this kata, try converting 12-hour time to 24-hour time:

https://www.codewars.com/kata/converting-12-hour-time-to-24-hour-time/train/python

Source: codewars | Difficulty: EASY

Starter code: def to12hourtime(t):
	

Solutions:
from datetime import datetime

def to12hourtime(t):
	return datetime.strptime(t, '%H%M').strftime('%I:%M %p').lstrip('0').lower()


def to12hourtime(t):
	hour = int(t[:2])
	if hour >= 12:
		hour -= 12
		suf = 'pm'
	else:
		suf = 'am'
	if hour == 0:
		hour = 12
	return '%s:%s %s' % (hour, t[2:], suf)


from datetime import datetime as dt

def to12hourtime(t):
	return dt.strptime(t, '%H%M').strftime('%-I:%M %p').lower()


def to12hourtime(timestring):
	print(timestring)
	hour = int(timestring[:2])
	mins = timestring[2:]
	if hour >= 12:
		noon = 'pm'
		hour -= 12
	else:
		noon = 'am'
	if hour == 0:
		hour = 12
	return '{}:{} {}'.format(hour, mins, noon)


from datetime import datetime
to12hourtime = lambda ts: str(datetime.strptime(ts, '%H%M').strftime('%-I:%M %p').lower())


def to12hourtime(s):
	(h, m) = divmod(int(s), 100)
	(p, h) = divmod(h, 12)
	return '{}:{:02} {}m'.format(h or 12, m, 'p' if p else 'a')


def to12hourtime(timestring):
	h = int(timestring[:2])
	return '{}:{} {}m'.format(h % 12 or 12, timestring[2:], 'ap'[h > 11])


def to12hourtime(hhmm):
	(hh, mm) = (int(hhmm[:2]), int(hhmm[2:]))
	return '{}:{:02} {}'.format(hh - 12 if hh > 12 else hh, mm, ['am', 'pm'][hh >= 12]) if hh else '12:{:02} am'.format(mm)


def to12hourtime(time_string):
	hour_str = time_string[0] + time_string[1]
	minute_str = time_string[2] + time_string[3]
	if int(hour_str) < 12:
		if int(hour_str) == 0:
			hour_str = 12
		return '%s:%s am' % (int(hour_str), minute_str)
	else:
		hour = int(hour_str) - 12
		if hour == 0:
			hour = 12
		return '%s:%s pm' % (hour, minute_str)