Adventures in Machine Learning

Python strftime() Function: A Comprehensive Guide for Timestamp Formatting

Python strftime() Function and Time Module: A Comprehensive Guide

Python is a popular programming language that boasts a vast range of built-in functions and modules for handling various use cases. One such module is the time module, which provides time-related functions and data conversions.

The strftime() function is a versatile feature of this module that enables developers to format timestamps as per their specific requirements. In this article, we’ll explain the Python strftime() function, dive into its various use cases, and explore the time module’s functionality.

Understanding Python strftime() Function

The strftime() function is used to format timestamps as per specific format codes. The function requires a timestamp and a format code as an input and returns a formatted string.

Developers commonly use this function to display timestamps in a user-readable form. The function is available in the datetime Python module and can be imported using the following code:

from datetime import datetime

Variant 1: Getting Current Time

The most common use case for the Python strftime() function is to obtain the current system timestamp and format it using format codes. To retrieve the current time, we’ll use the datetime.now() function along with strftime() function.

The following code shows how to obtain the current time and represent it in a string format using Python strftime():

from datetime import datetime
current_time = datetime.now()
formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted Time:", formatted_time)

Output:

Formatted Time: 2022-01-08 12:30:45

In the above example, we’ve used the format codes %Y, %m, %d, %H, %M, and %S to represent the year, month, day, hour, minute, and second respectively.

Variant 2: Handling Pre-defined Timestamp

In certain scenarios, we have a pre-defined timestamp that needs to be formatted using strftime() function.

To do this, we can use the datetime.fromtimestamp() function to create a datetime object, which can then be formatted using the strftime() function. Here’s an example:

from datetime import datetime
timestamp = 1641674407
dt_object = datetime.fromtimestamp(timestamp)
formatted_time = dt_object.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted Time:", formatted_time)

Output:

Formatted Time: 2022-01-08 12:30:45

Using Different Format Codes with Python strftime() Function

Now, let’s get into some examples that demonstrate how to use different format codes with Python strftime() function to represent timestamps in varied formats.

Example 1: Displaying Current Date using %A Format Code

The %A format code is used to represent the current day of the week, spelled out in full.

Here’s an example:

from datetime import datetime
current_date = datetime.now()
formatted_date = current_date.strftime("%A")
print("Current Day: ", formatted_date)

Output:

Current Day: Saturday

Example 2: Displaying Current Localtime using %c Format Code

The %c format code is used to display the current local date and time in a preferred format. Here’s an example:

from datetime import datetime
current_time = datetime.now()
formatted_time = current_time.strftime("%c")
print("Formatted Time:", formatted_time)

Output:

Formatted Time: Sat Jan  8 12:30:45 2022

Example 3: Representing Time in a 24-hour Format using %R Format Code

The %R format code is used to display time in 24-hour format (hours and minutes), without the seconds. Here’s an example:

from datetime import datetime
current_time = datetime.now()
formatted_time = current_time.strftime("%R")
print("Formatted Time:", formatted_time)

Output:

Formatted Time: 12:30

Example 4: Displaying Time in H:M:S Format along with AM/PM using %r Format Code

The %r format code is used to represent time in a 12-hour clock format (hours, minutes, and seconds) with AM/PM. Here’s an example:

from datetime import datetime
current_time = datetime.now()
formatted_time = current_time.strftime("%r")
print("Formatted Time:", formatted_time)

Output:

Formatted Time: 12:30:45 PM

Example 5: Displaying Local Date and Time

The %x, %X, %p format codes are used to represent the local date, local time, and AM/PM respectively. Here’s an example:

from datetime import datetime
current_time = datetime.now()
formatted_time = current_time.strftime("%x %X %p")
print("Formatted Time:", formatted_time)

Output:

Formatted Time: 01/08/22 12:30:45 PM

Python Time Module

The time module provides several additional features to handle time-related operations. The module provides time-related functions such as sleep() to pause the execution for a specified time period, time() to retrieve the current timestamp, localtime() to retrieve the local time, and strftime() for time formatting.

Here’s an example that demonstrates how to use the time module to display the current timestamp in seconds:

import time
print("Current Timestamp: ", int(time.time()))

Output:

Current Timestamp: 1641673348

Timestamp manipulation with time module is another useful aspect of the time module. Timestamp manipulation includes different operations such as timestamp addition, subtraction, date addition, and subtraction, time zone conversion, and more.

Conclusion

In this article, we have learned how to use the Python strftime() function and explored different format codes to represent timestamps in varied formats. We have also explored the time module’s functionality and demonstrated how to retrieve the current timestamp in seconds.

The time module has powerful features for timestamp manipulation that allows for making advanced calculations and conversions, which is an essential skill for developers working on time-related applications. In summary, the Python strftime() function and time module have proved to be versatile and valuable tools for timestamp and time-related operations.

With the strftime() function, developers can retrieve and format timestamps based on specific format codes. The time module provides a variety of functions for time-related operations, including timestamp manipulation, which is crucial for time-related applications.

Overall, understanding these functions will aid in the development of more efficient and accurate time-related applications.

Popular Posts