Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
24-hour time in Python
Converting 12-hour time format to 24-hour format is a common task in Python programming. The 12-hour format uses AM/PM suffixes, while 24-hour format uses hours from 00 to 23.
So, if the input is like "08:40pm", then the output will be "20:40".
Algorithm
To solve this, we will follow these steps ?
Extract hour from the time string and apply modulo 12 to handle 12 AM/PM cases
Extract minutes from the time string
If the suffix is 'p' (PM), add 12 to the hour
Return the formatted 24-hour time
Example
Let us see the following implementation to get better understanding ?
class Solution:
def solve(self, s):
hour = int(s[:2]) % 12
minutes = int(s[3:5])
if s[5] == 'p':
hour += 12
return "{:02}:{:02}".format(hour, minutes)
ob = Solution()
print(ob.solve("08:40pm"))
print(ob.solve("12:30am"))
print(ob.solve("12:15pm"))
print(ob.solve("01:45am"))
20:40 00:30 12:15 01:45
Using datetime Module
Python's datetime module provides a more robust approach for time conversion ?
from datetime import datetime
def convert_to_24hour(time_str):
# Parse 12-hour format and convert to 24-hour format
time_obj = datetime.strptime(time_str, "%I:%M%p")
return time_obj.strftime("%H:%M")
# Test with different time formats
times = ["08:40pm", "12:30am", "12:15pm", "01:45am"]
for time in times:
result = convert_to_24hour(time)
print(f"{time} ? {result}")
08:40pm ? 20:40 12:30am ? 00:30 12:15pm ? 12:15 01:45am ? 01:45
Comparison
| Method | Advantages | Best For |
|---|---|---|
| Manual Parsing | Simple, fast, no imports | Basic time conversion |
| datetime Module | Handles edge cases, robust | Production applications |
Conclusion
Both methods effectively convert 12-hour to 24-hour format. Use manual parsing for simple cases or the datetime module for more robust time handling with proper error checking.
