TrucoManso: Transformar el tiempo en formato 24h a formato 12h (Python)

Truco manso para transformar una cadena de tiempo en formato de 24h en formato de 12h (AM/PM)


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

Y un ejemplo de uso:

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

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

Trackback URL

, ,

No Comments on "TrucoManso: Transformar el tiempo en formato 24h a formato 12h (Python)"

Hi Stranger, leave a comment:

ALLOWED XHTML TAGS:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Subscribe to Comments