Python program to convert time from 12 hour to 24 hour format
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
Approach : 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 :
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:
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.
Approach#3: 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.
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
Time complexity: O(1)
Space complexity: O(1)
METHOD 4:Using .split
The approach of this code is to use the datetime module to convert the input time string to a datetime object, and then format the object into a string in 24-hour format using the strftime method.
1.Define the convert_12_to_24 function that takes a time string in 12-hour format as input.
2.Use the datetime module to parse the input time string into a datetime object.
3.Format the datetime object into a string in 24-hour format using the strftime method.
4.Return the 24-hour format string as the output of the function.
5.Call the convert_12_to_24 function with the input time strings and print the input and output times.
Input time: 11:21:30 PM Output time: 23:21:30 Input time: 12:12:20 AM Output time: 00:12:20
The time complexity of this code is O(1) since the time it takes to convert the input time string to a datetime object and format it into a string in 24-hour format is constant.
The space complexity of this code is O(1) since the memory used by the function is constant and does not depend on the input size.
Please Login to comment...