5 Best Ways to Extract the Hour from Time in Python

πŸ’‘ Problem Formulation: When working with time in Python, you might find yourself needing to extract the current hour or the hour from a given timestamp. The desired output is to obtain the hour as an integer between 0 and 23. This article guides you through five different methods to achieve this, whether you are dealing with the current time or parsing timestamps.

Method 1: Using datetime.now() and strftime

This method utilizes the datetime module to get the current local date and time, and then formats it to extract the hour using strftime(), which formats a time according to a specified format string.

Here’s an example:

from datetime import datetime

current_hour = datetime.now().strftime('%H')
print("Current hour:", current_hour)

Output: Current hour: 15

The %H format code in strftime() is used to represent the hour (24-hour clock) as a zero-padded decimal number. This code snippet retrieves the current local time, and then extracts and prints the hour.

Method 2: Using time module and localtime

Here we make use of the legacy time module, which provides a function localtime() that returns the local time in the form of a struct_time object from which the hour can be accessed.

Here’s an example:

import time

local_time = time.localtime()
current_hour = local_time.tm_hour
print("Current hour:", current_hour)

Output: Current hour: 15

The tm_hour attribute of the time.struct_time object is used to get the hour. This example extracts the current hour from the system’s local time.

Method 3: Using datetime.now() and hour attribute

Similar to Method 1, this method also uses datetime.now() but directly accesses the hour attribute of the datetime object without the need for formatting.

Here’s an example:

from datetime import datetime

current_hour = datetime.now().hour
print("Current hour:", current_hour)

Output: Current hour: 15

This approach is straightforward and efficient as it uses the hour attribute of the datetime object to directly obtain the current hour.

Method 4: Parsing a Given Timestamp

When you’re working with a specific timestamp string, the datetime.strptime() function is employed to parse the timestamp into a datetime object, from which the hour can be extracted.

Here’s an example:

from datetime import datetime

timestamp = "2023-04-12 15:45:00"
dt_object = datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S')
hour = dt_object.hour
print("Hour from timestamp:", hour)

Output: Hour from timestamp: 15

The strptime() function allows for custom timestamp formats, and in this case, it’s used to extract the hour from a predefined timestamp string.

Bonus One-Liner Method 5: Using time and slicing

This one-liner uses the time module to format the local time into a string and then slices the string to get the hour.

Here’s an example:

import time

current_hour = time.strftime('%H', time.localtime())
print("Current hour:", current_hour[:2])

Output: Current hour: 15

The output of time.strftime() is formatted to only include the hour, which is then extracted using simple string slicing.

Summary/Discussion

  • Method 1: datetime.now() and strftime. Strengths: Flexible formatting options. Weaknesses: Requires a formatting string.
  • Method 2: time module and localtime. Strengths: Provides additional time components easily. Weaknesses: More verbose than other datetime methods.
  • Method 3: datetime.now() and direct hour attribute access. Strengths: Simple and direct. Weaknesses: Less flexible compared to strftime.
  • Method 4: Parsing a given timestamp. Strengths: Useful for working with non-current timestamps. Weaknesses: Requires knowledge of the timestamp format.
  • Method 5: One-liner using time and slicing. Strengths: Concise. Weaknesses: Less readable and might be prone to errors if not used carefully.