English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python program to convert time from12Convert hour to24Hour format

Given PC time, it will be converted to24hour format. Here, we will apply string slicing.

Here, if the time is PM, then according to the rule, then add the hour part12; If the time is AM, do not add it.

Example

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

Algorithm

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]
      else:
      return str(int(str1[:2)] + 12) + str1[2:8]
   dt = datetime.datetime.now()
print("Conversion Of Time ::", timeconvert(dt.strftime("%H:%M:%S")))

Output Result

Conversion Of Time :: 24:04:53