
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert Time from 12-Hour to 24-Hour Format in Python
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
Advertisements