Python program to convert time from 12 hour to 24 hour format

PythonProgrammingServer Side Programming

Given a PC's time and it converted to 24 hour format. Here we are applying string slicing.

Here we follow the rules if time is PM then add 12 with hour part and if time is AM then don't add.


Input: 12:20:20 PM
Output: 24:20:20


Step 1: Input current datetime.
Step 2: Extract only time from datetime format.
Step 3: Using string slicing check last two words PM or AM.
Step 4: if last two word is PM then add 12 and if word are AM then don't add it.

Example Code

import datetime
   def timeconvert(str1):
      if str1[-2:] == "AM" and str1[:2] == "12":
         return "00" + str1[2:-2]
      elif str1[-2:] == "AM":
         return str1[:-2]
      elif str1[-2:] == "PM" and str1[:2] == "12":
         return str1[:-2]
      return str(int(str1[:2]) + 12) + str1[2:8]
print("Conversion Of Time ::",timeconvert(dt.strftime("%H:%M:%S")))


Conversion Of Time :: 24:04:53
Updated on 26-Jun-2020 09:28:24