5 Best Ways to Convert Time from 12 Hour to 24 Hour Format in Python

πŸ’‘ Problem Formulation: Converting time from a 12-hour clock (AM/PM) to a 24-hour clock is a common task in software development. This article helps Python programmers make such conversions with various methods. For instance, converting “02:15 PM” should yield the 24-hour format result “14:15”.

Method 1: Using datetime.strptime() and datetime.strftime()

This method leverages the datetime module’s strptime() method to parse the 12-hour time string into a datetime object and then outputs it in 24-hour format using the strftime() method.

Here’s an example:

from datetime import datetime

def convert_to_24hr(time_str):
    return datetime.strptime(time_str, "%I:%M %p").strftime("%H:%M")

print(convert_to_24hr("02:15 PM"))

Output: 14:15

In this code snippet, the function convert_to_24hr takes a string representing the time in 12-hour format and returns a string with the time in 24-hour format. The parsing and formatting are handled by strptime and strftime methods, respectively, making the code simple and readable.

Method 2: Using regular expressions and string formatting

This method utilizes the re module to extract the hours, minutes, and AM/PM indicator, then converts the hours to 24-hour format and formats the result as a string.

Here’s an example:

import re

def convert_to_24hr_regex(time_str):
    matches = re.match(r'(\d{1,2}):(\d{2}) (\w{2})', time_str)
    hour, minute, period = matches.groups()
    hour = int(hour)
    hour = hour % 12 + (period.upper() == 'PM') * 12
    return f"{hour:02d}:{minute}"

print(convert_to_24hr_regex("02:15 PM"))

Output: 14:15

In this code example, the regular expression matches the 12-hour format time string, the hour is adjusted based on whether it’s AM or PM, then returns the result using string formatting. It’s a powerful technique for working with strings and performing custom parsing logic.

Method 3: Manual String Manipulation

By manually splitting the string and adjusting the hours depending on the AM/PM indicator, one can use basic string manipulation to achieve the conversion, without importing additional modules.

Here’s an example:

def convert_to_24hr_manual(time_str):
    parts = time_str.split()
    hour_min = parts[0].split(':')
    hour = int(hour_min[0]) % 12 + (parts[1].upper() == 'PM') * 12
    return f"{hour:02d}:{hour_min[1]}"

print(convert_to_24hr_manual("02:15 PM"))

Output: 14:15

This code snippet splits the input string to get the hours, minutes, and AM/PM indicator separately. It then adjusts the hour value and outputs the time in 24-hour format using string formatting. This is a straightforward approach that is easy to understand.

Method 4: Using time.strptime() and time.strftime()

This method is similar to Method 1 but uses the time module instead. The strptime() function parses the time string, and strftime() converts it to the desired 24-hour format.

Here’s an example:

import time

def convert_to_24hr_time_module(time_str):
    tt = time.strptime(time_str, "%I:%M %p")
    return time.strftime("%H:%M", tt)

print(convert_to_24hr_time_module("02:15 PM"))

Output: 14:15

Here, the time.strptime() function creates a time tuple from the 12-hour time string, and time.strftime() formats it back into a string, but in 24-hour format. This method is quite concise and leverages built-in Python modules efficiently.

Bonus One-Liner Method 5: Using datetime and formatted string literals

Combining Method 1 with Python’s formatted string literals can lead to a compact one-liner solution.

Here’s an example:

from datetime import datetime

convert_to_24hr_one_liner = lambda time_str: datetime.strptime(time_str, "%I:%M %p").strftime("%H:%M")
print(convert_to_24hr_one_liner("02:15 PM"))

Output: 14:15

This one-liner uses a lambda function to compress the conversion logic into a single line. It’s elegant and practical for use cases where code brevity is preferred and can be utilized in more complex expressions or functions.

Summary/Discussion

  • Method 1: Using datetime.strptime() and datetime.strftime(). Strengths: Readable and straightforward using powerful datetime functions. Weaknesses: Slightly longer code compared to one-liners.
  • Method 2: Using regular expressions and string formatting. Strengths: Very flexible and can handle irregular input formats. Weaknesses: Regular expressions can be difficult to maintain and understand for some developers.
  • Method 3: Manual String Manipulation. Strengths: Does not require importing any modules and is easy to understand. Weaknesses: Code can become cumbersome with more complex time string manipulations.
  • Method 4: Using time.strptime() and time.strftime(). Strengths: Concise and utilizes Python’s standard time module. Weaknesses: Not as feature-rich as the datetime module.
  • Bonus Method 5: Using datetime and formatted string literals. Strengths: Extremely concise one-liner. Weaknesses: Lambda may be less readable for novice programmers.