Friday, May 15, 2020

Python Convert 12 Hour to 24 Hour Time

For computation purposes, 24 hour time works better. Here is a function to convert the 12 Hour time String to 24 hour time string.
def time_convert_12_24(self,str_time):
    
    time_arr = str_time.split()  # split by space    n = time_arr[0].count(':')
    time_str : str ='' 
    if n == 1 :
       #5:30        
       time_str = time_arr[0]+':00'     
    elif n == 0 :
       #5 
       time_str = time_arr[0]+':00:00'     
    else :
       time_str = time_arr[0]
    #change 12:00 am to 00:00
    if time_arr[1].upper() == 'AM' and time_str[:1] == "12":
        "00" + time_str[2:-2]
    # add 12 hour to PM hours
    if time_arr[1].upper() == 'PM' :
        str_part = time_str.split(':')
        if int(str_part[0]) != 12 :
            return str(int(str_part[0]) + 12) +':'+str_part[1] + ':'+ str_part[2]
        else :
            return time_str
    else :
        return time_str

No comments: