0

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
Asma
  • 137
  • 3
  • 15
  • Does this answer your question? [Convert 12 hour into 24 hour times](https://stackoverflow.com/questions/19229190/convert-12-hour-into-24-hour-times) – FObersteiner Oct 19 '21 at 10:58

2 Answers2

3

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
krmogi
  • 2,588
  • 1
  • 10
  • 26
  • 1
    I'd do this as a one-liner: `return datetime.strftime(datetime.strptime(time, "%I:%M:%S %p"), "%H:%M:%S")`. (With a little bit of whitespace to make it easier to parse visually.) – Samwise Oct 18 '21 at 23:32
1
    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)