5 Best Ways to Handle 24-Hour Time in Python

Rate this post

πŸ’‘ Problem Formulation: Working with time in programming often necessitates converting between different formats. In this article, we discuss how to handle 24-hour time format in Python. The article addressed the conversion of time data into the 24-hour format (e.g., converting “2:30 PM” to “14:30”), a common requirement for logging, scheduling, and time arithmetic.

Method 1: Using datetime.strptime and datetime.strftime

This method utilizes Python’s datetime module, specifically the strptime method to parse a string representing a time according to a format, and the strftime method to format the time object as a string. It is highly reliable and customizable to various time formats.

Here’s an example:

from datetime import datetime

input_time = "2:30 PM"
time_object = datetime.strptime(input_time, '%I:%M %p')
output_time = time_object.strftime('%H:%M')

print(output_time)

Output:

14:30

In the code snippet above, strptime is used to convert the input string into a time object by providing the specific format, and then strftime to output it in 24-hour format. %I is for 12-hour format, %M for minutes, %p for AM/PM notation, and %H for 24-hour format.

Method 2: Using time.strptime and time.strftime

Similar to datetime, the time module’s strptime and strftime functions can be used to parse and format times. This method is good for simple time conversion when no date information is required.

Here’s an example:

import time

input_time = "2:30 PM"
time_struct = time.strptime(input_time, '%I:%M %p')
output_time = time.strftime('%H:%M', time_struct)

print(output_time)

Output:

14:30

This code snippet also parses the time string into a struct_time object using strptime and formats it back into a string with strftime. The format specifiers are used similarly to the datetime module’s.

Method 3: Using pandas.to_datetime()

The pandas library provides vectorized time conversion features which can be particularly useful when dealing with series or dataframes containing multiple time strings. pandas.to_datetime() can convert a Series or DataFrame column to datetime, and dt.strftime method to format it.

Here’s an example:

import pandas as pd

input_time = "2:30 PM"
time_series = pd.Series([input_time])
output_series = pd.to_datetime(time_series).dt.strftime('%H:%M')

print(output_series[0])

Output:

14:30

In the example, pd.to_datetime() is used to convert the Pandas Series of time string into datetime objects, which are then formatted to a 24-hour time string with dt.strftime.

Method 4: Using pytz for Time Zone Conversion

When time zone conversion is required along with the time formatting, pytz library is indispensable. In conjunction with datetime, it accurately handles timezone conversions. After assigning a timezone, convert the time as needed and then format it.

Here’s an example:

from datetime import datetime
import pytz

input_time = "2:30 PM"
time_object = datetime.strptime(input_time, '%I:%M %p')
time_object = time_object.replace(tzinfo=pytz.timezone('US/Eastern'))
output_time = time_object.astimezone(pytz.utc).strftime('%H:%M')

print(output_time)

Output:

18:30

In this snippet, we first parse the time string into a datetime object, then set its timezone to ‘US/Eastern’. Finally, we convert it to UTC (which is in a 24-hour format) using astimezone() and format with strftime.

Bonus One-Liner Method 5: Using f-strings with datetime

Python 3.6 introduced f-strings, a new way to format strings using expressions evaluated at runtime. By combining f-strings with the datetime module, one can convert 12-hour time strings to 24-hour format in a neat one-liner.

Here’s an example:

from datetime import datetime

input_time = "2:30 PM"
output_time = f"{datetime.strptime(input_time, '%I:%M %p').strftime('%H:%M')}"

print(output_time)

Output:

14:30

This one-liner code snippet does everything inline. The strptime function parses the given time string to a datetime object, and immediately the strftime function is called within the f-string to format it into 24-hour mode.

Summary/Discussion

  • Method 1: datetime.strptime and datetime.strftime. Comprehensive and works well with dates included. May be too elaborate for simple time conversions.
  • Method 2: time.strptime and time.strftime. More lightweight than datetime, but lacks date handling capabilities. Ideal for time-only operations.
  • Method 3: pandas.to_datetime(). Excellent for batch conversions of time series data. Overhead of using pandas may not be necessary for single time strings.
  • Method 4: pytz with datetime. Best for timezone aware conversions. Requires an additional library and is more complex.
  • Bonus Method 5: f-strings with datetime. Clean and concise, great for simple inline use. Lacks readability for complex formatting.