The Wayback Machine - https://web.archive.org/web/20240918211226/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
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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
Python program to find difference between current time and given time
Given two times h1:m1 and h2:m2 denoting hours and minutes in 24 hours clock format. The current clock time is given by h1:m1. The task is to calculate the difference between two times in minutes and print the difference between two times in h:m format. Examples: Input : h1=7, m1=20, h2=9, m2=45 Output : 2 : 25 The current time is 7 : 20 and given
2 min read
Convert an image into jpg format using Pillow in Python
Let us see how to convert an image into jpg format in Python. The size of png is larger when compared to jpg format. We also know that some applications might ask for images of smaller sizes. Hence conversion from png(larger ) to jpg(smaller) is needed. For this task we will be using the Image.convert() method of the Pillow module. Algorithm : Impo
2 min read
Convert datetime string to YYYY-MM-DD-HH:MM:SS format in Python
In this article, we are going to convert the DateTime string into the %Y-%m-%d-%H:%M:%S format. For this task strptime() and strftime() function is used. strptime() is used to convert the DateTime string to DateTime in the format of year-month-day hours minutes and seconds Syntax: datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S") strftime() is used t
2 min read
Convert "unknown format" strings to datetime objects in Python
In this article, we are going to see how to convert the "Unknown Format" string to the DateTime object in Python. Suppose, there are two strings containing dates in an unknown format and that format we don't know. Here all we know is that both strings contain valid date-time expressions. By using the dateutil module containing a date parser that ca
3 min read
Convert a Bytes Array into Json Format in Python
In Python, dealing with bytes data is common, and converting a bytes array to JSON format is a frequent task. In this article, we will see how to convert a bytes array into JSON format in Python. Python Convert a Bytes Array into JSON FormatBelow are some of the ways by which we can convert a bytes array into JSON format in Python: Using decode and
3 min read
How to Convert Excel to XML Format in Python?
Python proves to be a powerful language when the requirement is to convert a file from one format to the other. It supports tools that can be employed to easily achieve the functionality. In this article, we'll find out how we will convert from an Excel file to Extensible terminology (XML) files with Python. Modules neededOpenPyXL helps in interact
3 min read
Get the Hour from timestamp in Pandas
Let's see how to extract the hour from a timestamp in Pandas, with the help of multiple examples. Example 1 : pandas.timestamp.now() takes timezone as input and returns current timestamp object of that timezone. # importing the module import pandas as pd # input current timestamp date = pd.Timestamp.now() print("currentTimestamp: ", date)
2 min read
Wand - Convert image format
Image Format describes how an image data is being stored. Different image formats have different merits and demerits. There are around 7 most common image formats which are used in different cases. For example - The advantage of JPEG format is that it supports 24-bit color with up to 16 million colors. Thus, having high resolution. While PNG format
1 min read
Pandas Series dt.to_period() Method | Convert DateTime to Period Format
The Pandas dt.to_period() method converts the underlying data of the given Series object to PeriodArray/Index at a particular frequency. It is used to convert a DateTime series to a period series with a specific frequency, such as daily, monthly, quarterly, or yearly periods. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-12-31', '201
2 min read
Convert the column type from string to datetime format in Pandas dataframe
While working with data in Pandas, it is not an unusual thing to encounter time series data, and we know Pandas is a very useful tool for working with time-series data in Python.Let's see how we can convert a dataframe column of strings (in dd/mm/yyyy format) to datetime format. We cannot perform any time series-based operation on the dates if they
5 min read
Python program to print number of bits to store an integer and also the number in Binary format
Given an integer, the task is to write a Python program to print the number of bits to store that integer and also print the same number in Binary format. Example: Input: n = 10 Output: Number of bits to store the number: 4 Binary value: 0b1010 Input: n = 120 Output: Number of bits to store the number: 7 Binary value: 0b1111000 The Task can be done
4 min read
Python program to Represent Negative Integers in binary format
Given a Negative Integer, the task is to write a Python program to convert the integer into binary format. Examples: Input: -14 Output: -1110 Input: -12 Output: -1100 Input: -32 Output: -100000 Let's implement this for the number in different ways : Method 1: Using format specifier 'b' In format specifier type b is used to convert the integer into
1 min read
Python program to print the dictionary in table format
Given a Dictionary. The task is to print the dictionary in table format. Examples: Input: {1: ["Samuel", 21, 'Data Structures'], 2: ["Richie", 20, 'Machine Learning'], 3: ["Lauren", 21, 'OOPS with java'], }Output: NAME AGE COURSE Samuel 21 Data Structures Richie 20 Machine Learning Lauren 21 OOPS with java Method 1: Displaying results by iterating
2 min read
Time Functions in Python | Set 1 (time(), ctime(), sleep()...)
Python has defined a module, "time" which allows us to handle various operations regarding time, its conversions and representations, which find its use in various applications in life. The beginning of time started measuring from 1 January, 12:00 am, 1970 and this very time is termed as "epoch" in Python. Operations on Time in Python Python time.t
4 min read
Python | time.time() method
Time module in Python provides various time-related functions. This module comes under Python’s standard utility modules. time.time() method of Time module is used to get the time in seconds since epoch. The handling of leap seconds is platform dependent. Note: The epoch is the point where the time starts, and is platform dependent. On Windows and
2 min read
How To Highlight a Time Range in Time Series Plot in Python with Matplotlib?
A time series plot is a plot which contains data which is being measured over a period of time, for example, a gross domestic product of a country, the population of the world and many other data. Sometimes we want to highlight a specific period of the timeline so that it is easier for the observer to read specific data. We can highlight a time ran
4 min read
How to convert date and time with different timezones in Python?
In this article, we will discuss how to convert date and time with different timezones in Python. To do this we will use one of the modules of python pytz . This module brings the Olson tz database into Python and this library allows accurate and cross-platform timezone calculations using Python. The method pytz.timezone() generates the current tim
2 min read
Time Complexity to Convert a Set to List in Python
Concerting a set to a list involves iterating through the elements of the set and adding them to a list. The time complexity of this operation is linear and depends on the size of the set. Let's denote the size of the set as n. The time complexity to convert a set to a list generally takes O(n) time. where n is the n of elements in the set. There a
3 min read
MoviePy – Changing Image and Time at same time of Video Clip
In this article we will see how we can change display frames and time line of the video file clip in MoviePy at a same time. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF's. We use fl_image method to alter the display frames and fl_time method to alter the time, although we can do these task
2 min read
Convert a series of date strings to a time series in Pandas Dataframe
During the analysis of a dataset, oftentimes it happens that the dates are not represented in proper type and are rather present as simple strings which makes it difficult to process them and perform standard date-time operations on them. pandas.to_datetime() Function helps in converting a date string to a python date object. So, it can be utilized
3 min read
Practice Tags :