7
\$\begingroup\$

Given a string in a 24 hour format the program outputs a 12 hour format. The rules are:

  • The output format must be 'hh:mm a.m.' if it represents before midday and 'hh:mm p.m.' after midday
  • When the hour is less than 10:00 you should not write a 0 before the hour, example: '9:05 a.m.'

For example:

12:30 → 12:30 p.m.
09:00 → 9:00 a.m.
23:15 → 11:15 p.m.

The code:

import datetime
def time_converter(time):
    midday_dt = datetime.datetime.strptime('12:00','%H:%M')
    time_dt = datetime.datetime.strptime(time, '%H:%M')

    if time_dt >= midday_dt:
        if time_dt >= datetime.datetime.strptime('13:00','%H:%M'):
            hours, minutes = clamp_to_twelve(time_dt, midday_dt)
            time = f'{hours}:{minutes}'
        time += ' p.m.'
    else:
        if time_dt < datetime.datetime.strptime('10:00','%H:%M'):
            time = time[1:]
        if is_midnight(time_dt):
            hours, minutes = clamp_to_twelve(time_dt, midday_dt)
            time = f'{hours}:{minutes:02d}'
        time += ' a.m.'
    return time

def clamp_to_twelve(time_dt, midday_dt):
    clamp_dt = time_dt - midday_dt
    minutes, seconds = divmod(clamp_dt.seconds, 60)
    hours, minutes = divmod(minutes, 60)
    return [hours, minutes]

def is_midnight(time_dt):
    return (time_dt >= datetime.datetime.strptime('00:00','%H:%M') and
        time_dt <= datetime.datetime.strptime('00:59','%H:%M'))

if __name__ == '__main__':
    assert time_converter('12:30') == '12:30 p.m.'
    assert time_converter('09:00') == '9:00 a.m.'
    assert time_converter('23:15') == '11:15 p.m.'
\$\endgroup\$
13
\$\begingroup\$

You don't need such a long program for such a short task. You can make it considerably shorter,

>>> from datetime import datetime
>>> d = datetime.strptime("10:30", "%H:%M")
>>> d.strftime('%I:%M %p').lstrip("0").replace(' AM', ' a.m.').replace(' PM', ' p.m.')
10:30 a.m.

>>> d = datetime.strptime("22:30", "%H:%M")
>>> d.strftime('%I:%M %p').lstrip("0").replace(' AM', ' a.m.').replace(' PM', ' p.m.')
10:30 p.m.

>>> d = datetime.strptime("09:00", "%H:%M")
>>> d.strftime('%I:%M %p').lstrip("0").replace(' AM', ' a.m.').replace(' PM', ' p.m.')
9:00 a.m.

The lstrip() function is to remove any cases of zero-paddings in front of the hours (basically, it removes zeros starting from the left side).

replace() is an inbuilt function in Python that returns a copy of the string where all occurrences of a substring are replaced with another substring.

Syntax - string.replace(old, new) (in my case - replaces all occurrences of AMand PM with a.m. and p.m.)

You can use strftime for your requirements and you can take a look at this too.

NOTE - Certain formats in the above-mentioned links only work on Linux (If you're using Linux, you can use %-I to remove the zero in front of the hours).

Hope this helps!

\$\endgroup\$
  • \$\begingroup\$ @enoy - If you liked this answer, please feel free to accept it (grants you a small rep bonus) :) \$\endgroup\$ – Justin May 27 at 11:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.