Home > database >  Change time from 12-h to 24-h format
Change time from 12-h to 24-h format

Time:10-19

I want to convert a time from 12-h format to 24-h format

This is my code:

def change_time(time):
    import datetime as dt
    FMT12 = '%H:%M:%S %p'
    FMT24 = '%H:%M:%S'
    # time is a string
    if time.find('PM') != -1: # if exists
        t1 = dt.datetime.strptime(time, FMT12)
        t2 = dt.datetime.strptime('12:00:00', FMT24)
        time_zero = dt.datetime.strptime('00:00:00', FMT24)
        return (t1 - time_zero   t2).time()
    else:
        return dt.datetime.strptime(time, FMT12).time()

This is the output :

print(change_time('09:52:08 PM')) # -> 21:52:08

So, this code is working, but I want a better version of it.

CodePudding user response:

Here is a much faster working method:

from datetime import datetime
def change_time(time):
    in_time = datetime.strptime(time, "%I:%M:%S %p")
    new_time = datetime.strftime(in_time, "%H:%M:%S")
    print(new_time)

change_time('09:52:08 PM')

Output:

>>> 21:52:08

CodePudding user response:

    def t12_to_24(time):
        am_or_pm = time[-2]   time[-1]
        time_update = ''
        if am_or_pm == 'am' or am_or_pm == 'AM':
                for i in time[0:-3]: 
                     time_update  = i
        elif am_or_pm == 'pm' or am_or_pm == 'PM':
                change = ''
                for i in time[0:2]:
                        change  = i
                c = 12   int(change)
                
                if c >= 24:
                     c = 24 - c
                c = list(str(c))
                for i1 in c: 
                         time_update  = i1
                for i2 in time[2:-3]:
                    time_update  = i2
                
        print(time_update)
time = list(input())
t12_to_24(time)
    
  • Related