Search code examples
pythontimereplacestrptimestrftime

Python Change the time AM to PM and Vice Versa


I have a list of time. I want all AM to be PM and all PM to AM.

Input
newtimes

Output
['10:31 PM', '10:03 PM', '12:26 AM', '07:40 PM', '09:32 PM']

Input

       for items in newtimes:
       newtimes1 = items.replace('AM','PM').replace('PM','AM')
       print(newtimes1)

Output i am getting:
10:31 AM
10:03 AM
12:26 AM
07:40 AM
09:32 AM

Am looking for the output such as:
10:31 AM
10:03 AM
12:26 PM
07:40 AM
09:32 AM


Solution

  • Just check before you replace:

    for old_time in old_times:
        if 'AM' in old_time:
            new_time = old_time.replace('AM', 'PM')
        else:
            new_time = old_time.replace('PM', 'AM')
        print(new_time)