MansoTrick: Convert 24h time string to 12h AM/PM format (Python)

Manso trick to convert from 24h time format to 12h (AM/PM) time format in Python


def ampmformat (hhmmss):
  """
    This method converts time in 24h format to 12h format
    Example:   "00:32" is "12:32 AM"
               "13:33" is "01:33 PM"
  """
  ampm = hhmmss.split (":")
  if (len(ampm) == 0) or (len(ampm) > 3):
    return hhmmss

  # is AM? from [00:00, 12:00[
  hour = int(ampm[0]) % 24
  isam = (hour >= 0) and (hour < 12)

  # 00:32 should be 12:32 AM not 00:32
  if isam:
    ampm[0] = ('12' if (hour == 0) else "%02d" % (hour))
  else:
    ampm[0] = ('12' if (hour == 12) else "%02d" % (hour-12))

  return ':'.join (ampm) + (' AM' if isam else ' PM')

Now some examples of the returned values:

ampmformat ("00:00:00") # returns "12:00:00 AM"
ampmformat ("12:00:00") # returns "12:00:00 PM"

ampmformat ("01:23:45") # returns "01:23:45 AM"
ampmformat ("13:23:45") # returns "01:23:45 PM"
ampmformat ("05:43:21") # returns "05:43:21 AM"
ampmformat ("17:43:21") # returns "05:43:21 PM"
    
ampmformat ("11:59:59") # returns "11:59:59 AM"
ampmformat ("23:59:59") # returns "11:59:59 PM"

Trackback URL

, ,

Comments are closed.