The Wayback Machine - https://web.archive.org/web/20240611212913/https://www.geeksforgeeks.org/python-program-convert-time-12-hour-24-hour-format/
Open In App

Python program to convert time from 12 hour to 24 hour format

Last Updated : 28 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a time in 12-hour AM/PM format, convert it to military (24-hour) time. Note : Midnight is 12:00:00 AM on a 12-hour clock and 00:00:00 on a 24-hour clock. Noon is 12:00:00 PM on 12-hour clock and 12:00:00 on 24-hour clock. Examples :

Input : 11:21:30 PM
Output : 23:21:30

Input : 12:12:20 AM
Output : 00:12:20

How to Convert AM/PM to 24 Hour Time

Whether the time format is 12 hours or not, can be found out by using list slicing. Check if last two elements are PM, then simply add 12 to them. If AM, then don’t add. Remove AM/PM from the updated time.   Below is the implementation : 

Python3




# Python program to convert time
# from 12 hour to 24 hour format
 
# Function to convert the date format
def convert24(str1):
     
    # Checking if last two elements of time
    # is AM and first two elements are 12
    if str1[-2:] == "AM" and str1[:2] == "12":
        return "00" + str1[2:-2]
         
    # remove the AM    
    elif str1[-2:] == "AM":
        return str1[:-2]
     
    # Checking if last two elements of time
    # is PM and first two elements are 12
    elif str1[-2:] == "PM" and str1[:2] == "12":
        return str1[:-2]
         
    else:
         
        # add 12 to hours and remove PM
        return str(int(str1[:2]) + 12) + str1[2:8]
 
# Driver Code        
print(convert24("08:05:45 PM"))


Output :

20:05:45

Time Complexity: O(1)

Auxiliary Space: O(1)

Here is another approach to the problem that uses the datetime module in Python to convert the time from 12-hour to 24-hour format:

Python3




from datetime import datetime
 
def convert24(time):
    # Parse the time string into a datetime object
    t = datetime.strptime(time, '%I:%M:%S %p')
    # Format the datetime object into a 24-hour time string
    return t.strftime('%H:%M:%S')
 
print(convert24('11:21:30 PM'))  # Output: '23:21:30'
print(convert24('12:12:20 AM'))  # Output: '00:12:20'


Output

23:21:30
00:12:20

This approach has the advantage of handling invalid time formats and edge cases, such as the time being in an invalid format or the hours being greater than 12. It also allows for the input time to be in any valid time format recognized by the datetime module, such as using a single digit for the hour or using a different separator between the time parts.

The time complexity of this approach is O(1), as it only involves parsing and formatting the time string.

Using regular expression

Use regular expressions to extract the hour, minute, second, and AM/PM parts from the input time string. Apply the necessary logic to convert the hour to 24-hour format. Format the hour, minute, and second parts into the desired 24-hour time format.

Algorithm

1. Use regular expressions to extract the hour, minute, second, and AM/PM parts from the input time string.
2. If AM/PM is “PM” and hour is not equal to 12, add 12 to the hour value
3. If AM/PM is “AM” and hour is equal to 12, set hour to 0
4. Format the time into 24-hour format and return the result

Python3




import re
 
def convert_to_24hour(time_str):
    hour, minute, second, am_pm = re.findall('\d+|\w+', time_str)
    hour = int(hour)
    if am_pm == 'PM' and hour != 12:
        hour += 12
    elif am_pm == 'AM' and hour == 12:
        hour = 0
    return f'{hour:02d}:{minute}:{second}'
print(convert_to_24hour('11:21:30 PM'))
print(convert_to_24hour('12:12:20 AM'))


Output

23:21:30
00:12:20

Time complexity: O(1)
Space complexity: O(1)



Previous Article
Next Article

Similar Reads

Pandas Series dt.hour | Extract Hour Part from Time Stamp
Pandas dt.hour attribute returns a NumPy array containing the hour of the DateTime in the underlying data of the given Series object. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = i
2 min read
Python program to print current hour, minute, second and microsecond
In this article, we are going to discuss how to print current hour, minute, second, and microsecond using Python. In order to print hour, minute and microseconds we need to use DateTime module in Python. Methods useddatetime.now().hour(): This method returns the current hour value of the datetime object.datetime.now().minute(): This method returns
4 min read
Python Program to Convert a Number into 32-Bit Binary Format
Binary representation is a fundamental concept in computer science, and converting numbers into binary format is a common task for programmers. In this article, we will explore some simple and generally used methods to convert a number into a 32-bit binary format using Python. Each method provides a unique approach to achieve the same result. Conve
3 min read
Convert Epoch Time to Date Time in Python
Epoch time, also known as Unix time or POSIX time, is a way of representing time as the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970. Converting epoch time to a human-readable date and time is a common task in programming, especially in Python. In this article, we will explore some si
3 min read
Time difference between expected time and given time
Given the initial clock time h1:m1 and the present clock time h2:m2, denoting hour and minutes in 24-hours clock format. The present clock time h2:m2 may or may not be correct. Also given a variable K which denotes the number of hours passed. The task is to calculate the delay in seconds i.e. time difference between expected time and given time. Ex
5 min read
Pandas Series dt.time | Extract Time from Time Stamp in Series
The Series.dt.time attribute returns a NumPy array containing time values of the timestamps in a Pandas series. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx sr = pd.to_datetime
2 min read
Python | Pandas DatetimeIndex.hour
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas DatetimeIndex.hour attribute outputs an Index object containing the hour values present in each of the entries of the DatetimeInd
2 min read
Python | Pandas Period.hour
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Period.hour attribute returns an integer value indicating the value of the hour in the given Period object. Syntax : Period.hourP
2 min read
Python | Pandas PeriodIndex.hour
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas PeriodIndex.hour attribute return the hour of the period for the given PeriodIndex object. Syntax : PeriodIndex.hour Parameters :
2 min read
Python | Pandas Timestamp.hour
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Timestamp.hour attribute return the value of the hour for the given Timestamp object. Syntax : Timestamp.hour Parameters : None R
2 min read
Article Tags :
Practice Tags :