- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python program to convert time from 12 hour to 24 hour format
In this article, we will learn how to convert time from 12 to 24 hours format. Let’s say we have the following input date in 12-hour format −
10:25:30 PM
The following is the output in 24-hour format −
22:25:30
Convert current time from 12 hour to 24 hour format
To convert time from 12 hour to 24 hour format, here’s the code −
Example
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("Current Date and Time = ",dt) print("24 hour format Time = ",timeconvert(dt.strftime("%H:%M:%S")))
Output
Current Date and Time = 2022-08-03 06:26:55.927011 24 hour format Time = 18:26:55
Convert current time from 12 hour to 24 hour format using strptime() method
To convert time from 12 hour to 24 hour format using a built-in method strptime() method, here’s the code −
Example
from datetime import * # Set the time in 12-hour format current_time = '5:55 PM' print("Time = ",current_time) # Convert 12 hour time to 24 hour format current_time = datetime.strptime(current_time, '%I:%M %p') print("Time in 24 hour format = ",current_time)
Output
Time = 5:55 PM Time in 24 hour format = 1900-01-01 17:55:00
- Related Articles
- C# program to convert time from 12 hour to 24 hour format
- C++ program to convert time from 12 hour to 24 hour format
- Convert time from 24 hour clock to 12 hour clock format in C++
- Converting 12 hour format time to 24 hour format in JavaScript
- How to convert 12-hour time scale to 24-hour time in R?
- Java Program to display time in 24-hour format
- Program to convert hour minutes’ time to text format in Python
- Java Program to display Time in 12-hour format
- 24-hour time in Python
- How to convert string to 24-hour datetime format in MySQL?
- Python Pandas - Format the Period object and display the Time with 24-Hour format
- Format hour in k (1-24) format in Java
- Format hour in kk (01-24) format in Java
- JavaScript program to convert 24 hours format to 12 hours
- MySQL convert timediff output to day, hour, minute, second format?

Advertisements