5 Best Ways to Access and Convert Time Using the Time Library in Python

πŸ’‘ Problem Formulation: When programming in Python, developers often need to interact with time for various purposes, like logging, timing operations, or interfacing with time-dependent APIs. This article demonstrates how to access the current time and convert between different time formats using Python’s built-in time library. For example, we might want to convert a time object into a human-readable string, or vice versa.

Method 1: Getting Current Time

Accessing the current time in Python is done using the time() function from the time library. The function returns the current time in seconds since the Epoch (a.k.a., Unix time). This method is particularly useful for timestamping events or calculating durations.

Here’s an example:

import time

current_time = time.time()

print(current_time)

Output:

1609459200.473845

This code snippet imports the time library and then uses the time() function to fetch the current time. The returned value is the number of seconds passed since January 1, 1970, 00:00 UTC.

Method 2: Converting Timestamp to Structured Time

The localtime() function converts a timestamp (seconds since the Epoch) to a time tuple in local time. This tuple has named fields for year, month, day, etc., making it easier to work with individual components of the time.

Here’s an example:

import time

timestamp = time.time()
structured_time = time.localtime(timestamp)

print(structured_time)

Output:

time.struct_time(tm_year=2023, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=1, tm_isdst=0)

This snippet converts the current timestamp to a more readable structured time object which can be accessed via its properties like tm_year, tm_mon, etc.

Method 3: Formatting Time as a String

To convert a time tuple or timestamp to a formatted string, we use strftime(). This function takes a format string and a time tuple, returning a string representing the time formatted according to the specified format.

Here’s an example:

import time

structured_time = time.localtime()
time_string = time.strftime("%Y-%m-%d %H:%M:%S", structured_time)

print(time_string)

Output:

"2023-01-01 00:00:00"

This code converts the structured time obtained from localtime() into a human-readable date and time string using the specified formatting.

Method 4: Parsing a String to Structured Time

To parse a string representing time into a structured time object, the strptime() function is used. It takes two arguments: the time string and the time format, and it returns a structured time object based on the given string.

Here’s an example:

import time

time_string = "2023-01-01 00:00:00"
structured_time = time.strptime(time_string, "%Y-%m-%d %H:%M:%S")

print(structured_time)

Output:

time.struct_time(tm_year=2023, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=1, tm_isdst=-1)

This code parses a given date and time string into a structured time object, which could be used for further manipulation or conversion.

Bonus One-Liner Method 5: Sleeping for an Interval

Using the sleep() function in Python’s time library, the program execution can be halted for a specified number of seconds. This function is handy when you need to create a delay or rate-limit a loop.

Here’s an example:

import time

print("Sleeping for 5 seconds...")
time.sleep(5)
print("Awake!")

Output:

Sleeping for 5 seconds... Awake!

In this brief example, the script will print a message, wait for 5 seconds, and then print another message.

Summary/Discussion

  • Method 1: Getting Current Time. Straightforward way to get the current Unix timestamp. Limited to providing seconds since the epoch.
  • Method 2: Converting Timestamp to Structured Time. Converts a timestamp to a structured time. Provides more detail than a timestamp but is limited to local time.
  • Method 3: Formatting Time as a String. Allows for easy reading and can be customized with different formats. Not suited for further time calculations.
  • Method 4: Parsing a String to Structured Time. Perfect for converting strings to a time format. It requires a correct format to parse correctly.
  • Method 5: Sleeping for an Interval. Useful for delays and timing control. It blocks program execution, which may not be desirable in all cases.