
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
24-hour time in Python
Suppose we have a string s. Here s is representing a 12-hour clock time with suffixes am or pm, we have to find its 24-hour equivalent.
So, if the input is like "08:40pm", then the output will be "20:40"
To solve this, we will follow these steps −
hour := (convert the substring of s [from index 0 to 2] as integer) mod 12
minutes := convert the substring of s [from index 3 to 5] as integer
if s[5] is same as 'p', then
hour := hour + 12
return the result as hour:minutes
Let us see the following implementation to get better understanding −
Example
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"))
Input
"08:40pm"
Output
20:40
- Related Articles
- Python program to convert time from 12 hour to 24 hour format
- How to convert 12-hour time scale to 24-hour time in R?
- Converting 12 hour format time to 24 hour format in JavaScript
- Java Program to display time in 24-hour format
- Convert time from 24 hour clock to 12 hour clock format in C++
- C++ program to convert time from 12 hour to 24 hour format
- C# program to convert time from 12 hour to 24 hour format
- Python Pandas - Format the Period object and display the Time with 24-Hour format
- How to Convert Time Format from 12 Hour to 24 Hour and Vice Versa in Excel?
- Non-24-Hour Sleep-Wake Disorder
- Format hour in k (1-24) format in Java
- Format hour in kk (01-24) format in Java
- Program to convert hour minutes’ time to text format in Python
- How to convert string to 24-hour datetime format in MySQL?
- Print the time an hour ago PHP?

Advertisements