Convert 12 hour into 24 hour times

后端 未结 12 722
走了就别回头了
走了就别回头了 2020-12-31 08:17

I\'m trying to convert times from 12 hour times into 24 hour times...

Automatic Example times:

06:35  ## Morning
11:35  ## Morning (If m2 is anywhe         


        
12条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-31 08:40

    To convert 12 hour time format into 24 hour time format

    ''' To check whether time is 'AM' or 'PM' and whether it starts with 12 (noon or morning). In case time is after 12 noon then we add
    12 to it, else we let it remain as such. In case time is 12 something in the morning, we convert 12 to (00) '''

    def timeConversion(s):

        if s[-2:] == 'PM' and s[:2] != '12':
            time = s.strip('PM')
            conv_time = str(int(time[:2])+12)+time[2:]
    
        elif s[-2:] == 'PM' and s[:2] == '12':
            conv_time = s.strip('PM')
    
        elif s[-2:] == 'AM' and s[:2] == '12':
            time = s.strip('AM')
            conv_time = '0'+str(int(time[:2])-12)+time[2:]
    
        else:
            conv_time = s.strip('AM')
            
        return conv_time
    

提交回复
热议问题