What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Date and Time Formatting in Python with strftime (With Code Example)

  • Nov 17, 2023
  • 7 Minutes Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Abhisek Ganguly
Date and Time Formatting in Python with strftime (With Code Example)

Handling date and time is an important part of many applications in the huge world of Python programming. The strftime function, which is present within the Python time module, stands out as a versatile solution for formatting date and time strings. We'll dive deep into the strftime in this blog, studying Python strftime format options, mastering date and time formatting, and exploring the art of converting date and time strings in Python.

What is strftime?

The strftime function, which stands for "string format time," is a method for representing date and time objects as strings in a user-specified format. This function is particularly useful when you want to present dates and times in a readable and customized manner. The basic syntax involves generating a struct_time object containing the current time and formatting it with strftime:

import time

current_time = time.localtime()
formatted_time = time.strftime(format, current_time)

 

Here, the format string is the key to unlocking different types of date and time representations. 

Python strftime Format Options

One of strftime's greatest strength is the wide range of format directives it offers. These instructions serve as the foundation for creating unique date and time displays. Let's look at some basic format choices:

%Y: Four-digit year

%mMonth as a zero-padded decimal

%d: Day of the month as a zero-padded decimal

%H: Hour (00-23)

%M: Minute(00-59)

%S: Second(00-59)

%a: Abbreviated weekday name

%A: Full weekday name

%b: Abbreviated month name

%B: Full month name

%Z: Time zone name

When used together, these instructions enable us to create a wide variety of date and time formats through creative combinations.

Date and Time Representations

The importance of strftime in creating date and time representations in programming goes beyond basic functionality; it includes a critical component of user experience and data interpretation. Clear and attractive ways of showing time improve how information is understood and used in apps. Date formatting not only improves the appearance of time-related data, but also ensures consistent output for better communication. The seamless integration of date and time formatting allows you to create a unified and user-friendly experience.

Let’s discuss how we can format the date and time using strftime.

Date Formatting

We can use the %Y-%m-%d %H:%M:%S format code to extract the year, month, day, hour, minute, and second from the date and time object. Let’s look at an example.

Code:

import time

current_time = time.localtime()

formatted_date = time.strftime("%Y-%m-%d", current_time)
print(f"Formatted Date: {formatted_date}")

 

Output:

Formatted Date: 2023-11-14

 

Time Formatting Example

To format the time, you can use various format codes depending on your requirements. For example, you can use %H for the hour in 24-hour format, %M for the minute, and %S for the second. Let's see an example:

Code:

import time

current_time = time.localtime()

formatted_time = time.strftime("%H:%M:%S", current_time)
print(f"Formatted Time: {formatted_time}")

 

Output:

Formatted Time: 16:30:00

 

Combined Date and Time Formatting Example

You can combine multiple format codes to create a more customized string representation of the date and time. Let's consider an example:

Code:

import time

current_time = time.localtime()

# Format: YYYY-MM-DD HH:MM:SS
formatted_datetime = time.strftime("%Y-%m-%d %H:%M:%S", current_time)
print(f"Formatted Date and Time: {formatted_datetime}")

 

Output:

Formatted Date and Time: 2023-11-14 16:30:00

 

These examples showcase the expressive power of strftime in creating visually appealing temporal representations.

Date and Time Strings

Date and time strings, beyond their basic representation of date and time information, become valuable assets when precisely structured with the 'strftime' module. These formatted strings in application logs give an organized and standardized record of occurrences, assisting you with debugging, monitoring, and performance analysis of your application. 

The refined presentation of timestamps in user interfaces improves user experience by making them more accessible and clear. The standardized output improves not only readability but also consistency, making it easier to analyze the date and time data across different components of an application.

Date and Time String Conversion

Date and time string conversion refers to the process of changing the way date and time information is represented in a format that is easily understandable by both humans and computers. This conversion allows the transformation between different representations of date and time, making it easier to manage, analyze, and display this information across various systems and applications. In Python, the strptime function is commonly used to convert date and time strings into structured objects, enabling easier manipulation and analysis of temporal data.

Date and Time String Conversion Example

Let’s see an example of the same.

Code:

import time

# String to struct_time
time_string = "2023-11-14 15:30:00"
parsed_time = time.strptime(time_string, "%Y-%m-%d %H:%M:%S")
print(f"Parsed Time: {parsed_time}")

 

Output:

Parsed Time: time.struct_time(tm_year=2023, tm_mon=11, tm_mday=14, tm_hour=15, tm_min=30, tm_sec=0, tm_wday=0, tm_yday=318, tm_isdst=-1)

 

We have used the strptime function from the time module to convert the "2023-11-14 15:30:00" string into a structured time format based on the provided format "%Y-%m-%d %H:%M:%S", displaying the parsed time as output.

Conclusion

In this article, we have explored the strftime() function in Python, which allows you to format date and time objects into a string representation. We have seen how to use various format codes to extract specific parts of the date and time and combine them to create customized and readable strings. By using strftime(), you can easily format dates and times according to your requirements, whether it's for displaying data, generating reports, or any other application that involves working with dates and times.

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Abhisek Ganguly
Passionate machine learning enthusiast with a deep love for computer science, dedicated to pushing the boundaries of AI through academic research and sharing knowledge through teaching.