Mastering the Python strftime() Function for Date Formatting

Advertisement

May 15, 2025 By Tessa Rodriguez

When working with dates and times in Python, you’ll often need to present them in a format that people can read. Computers like to store time in timestamps or datetime objects, but humans prefer something more recognizable—like “May 30, 2025” or “30/05/25.” That’s where the strftime() function comes in. It lets you take a datetime object and convert it into a string format of your choice.

If you've ever printed the date as of today or recorded timestamps in a non-standard layout, odds are you've employed strftime()—or will be short. This function is part of Python's standard datetime module and is simple yet flexible enough for a wide range of formatting needs.

Understanding the Basics of strftime()

The strftime() function stands for “string format time.” It's used to convert datetime objects into formatted strings based on specific formatting codes. These codes are made up of percentage signs followed by a character, each representing a different part of the date or time. For example, %Y gives you the full four-digit year, while %m gives you the month as a two-digit number.

To use strftime(), you initially require a datetime object. Python's datetime module offers this. After obtaining the object, calling strftime() on it with the formatting string gives back a simple string. Here's a basic example:

from datetime import datetime

now = datetime.now()

formatted = now.strftime("%Y-%m-%d %H:%M:%S")

print(formatted)

This will print something like 2025-05-30 14:45:22, depending on the current time when it runs.

The format string is what controls how the output looks. You can mix and match different codes to get exactly what you need. This makes strftime() particularly useful for displaying timestamps in logs, filenames, reports, or UI elements where readability matters.

Format Codes and How They Work

The power of strftime() lies in its many formatting options. There is a long list of codes that you can use, and each has a distinct purpose. Some of the more common codes include:

  • %Y: Four-digit year (e.g., 2025)
  • %y: Two-digit year (e.g., 25)
  • %m: Two-digit month (e.g., 05)
  • %d: Two-digit day of the month (e.g., 30)
  • %H: Hour in 24-hour format (e.g., 14)
  • %I: Hour in 12-hour format (e.g., 02)
  • %M: Minutes (e.g., 45)
  • %S: Seconds (e.g., 22)
  • %p: AM or PM
  • %A: Full weekday name (e.g., Friday)
  • %B: Full month name (e.g., May)

You can combine these codes in any order, adding your preferred separators, such as dashes, slashes, or colons. The structure is totally flexible. For instance, if you want a string like "Friday, May 30, 2025," you can use:

formatted = now.strftime("%A, %B %d, %Y")

This level of control is one reason why strftime() remains one of the most useful tools in Python’s date handling. It’s all about making time data more readable or fitting the specific format your application requires.

How to Effectively Use strftime() in Projects?

One of the most common uses of strftime() is logging. Let’s say you’re building an application that writes messages to a file. Having a well-formatted timestamp on each log entry helps track what happened and when. Using strftime() ensures that each timestamp follows a consistent format, whether that’s ISO standard or something more customized.

Another example is when creating filenames that include dates, like “backup_2025_05_30.zip.” Here, the strftime() function helps dynamically insert today’s date into the filename, so it’s easy to manage and sort later.

A common mistake new developers make is assuming the format codes are interchangeable with plain text. For example, writing %DD instead of %d won’t work. There’s a strict set of recognized codes, and anything outside of that is treated as regular text. If you see unexpected results, the first thing to check is your format string.

Timezones are another area to be careful about. The strftime() function works on datetime objects, but it doesn’t do timezone conversions by itself. If you need to show times in a different zone, make sure to convert the datetime object beforehand using a library like pytz or the zoneinfo module in Python 3.9 and later. Once the object has the correct timezone, strftime() will reflect that in the output if you use the %Z or %z codes.

Also worth noting: if your format string includes a fixed text pattern that looks like a format code—say, %Discount%—strftime() will try to interpret anything following a percent sign. To include a literal percent sign in your string, use %%.

Comparing strftime() with strptime()

The strftime() function has a close cousin called strptime(). While strftime() converts a datetime object to a string, strptime() does the reverse—it turns a formatted string into a datetime object. They are often used together when reading and writing date data.

For instance, if you have a string like “2025-05-30 14:45:22” and want to turn it into a datetime object, you’d use:

from datetime import datetime

date_string = "2025-05-30 14:45:22"

dt_object = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")

The format codes in strptime() must match the string exactly, or it will raise a ValueError. This is one area where beginners often stumble. If there’s an extra space or a wrong separator, Python won’t be able to parse the date.

Understanding both functions allows you to convert between datetime objects and strings with ease. It’s common to parse input with strptime() and then reformat it using strftime(). These two functions form a complete cycle for working with time data in Python.

Conclusion

Working with time isn’t always straightforward, but Python’s strftime() function helps smooth out a lot of the edges. It gives you the control to present dates and times exactly the way you want them, whether that’s for human eyes or machine logs. By using a mix of format codes, you can create consistent, readable time strings from any datetime object. The key is knowing what each code means and how they fit together. Once you’re familiar with the basics, strftime() becomes second nature. Pairing it with strptime() rounds out your date-handling skills, making it easy to switch between raw strings and datetime objects whenever needed.

Advertisement

Recommended Updates

Applications

Metabase: The Open-Source BI Tool for Simple Data Analysis

How the open-source BI tool Metabase helps teams simplify data analysis and reporting through easy data visualization and analytics—without needing technical skills

Technologies

Explore How Nvidia Maintains AI Dominance Despite Global Tariffs

Discover how Nvidia continues to lead global AI chip innovation despite rising tariffs and international trade pressures.

Applications

The Galaxy S24 Series: Samsung’s New Era of Intelligent Phones

Samsung launches world’s smartest AI phone with the new Galaxy S24 series, bringing real-time translation, smart photography, and on-device AI that adapts to your daily routine

Basics Theory

OpenAI for Businesses: Top Features, Benefits, and Use Cases

Discover OpenAI's key features, benefits, applications, and use cases for businesses to boost productivity and innovation.

Technologies

BigCodeBench Raises The Bar For Realistic Coding Model Evaluation Metrics

What makes BigCodeBench stand out from HumanEval? Explore how this new coding benchmark challenges models with complex, real-world tasks and modern evaluation

Applications

Google Launches Tools and Protocol for Building AI Agents

Google debuts new tools and an agent protocol to simplify the creation and management of AI-powered agents.

Applications

Compact Brilliance: How Phi-2 Is Changing Language Model Design

How Phi-2 is changing the landscape of language models with compact brilliance, offering high performance without large-scale infrastructure or excessive parameter counts

Technologies

Fast RAG on CPUs: Using Optimum Intel and Hugging Face Embeddings

How CPU Optimized Embeddings with Hugging Face Optimum Intel and fastRAG can run fast, low-cost RAG pipelines without GPUs. Build smarter AI systems using Intel Xeon CPUs

Technologies

Top 5 Compelling Reasons to Switch from VLOOKUP to INDEX MATCH in Excel

Why INDEX MATCH is often a better choice than VLOOKUP in Excel. Learn the top 5 reasons to use INDEX MATCH for more flexible, efficient, and reliable data lookups

Impact

How Hugging Face and FriendliAI Are Making AI Model Deployment Easier Than Ever

Hugging Face and FriendliAI have partnered to streamline model deployment on the Hub, making it faster and easier to bring AI models into production with minimal setup

Basics Theory

There’s No Official ChatGPT Windows App—Only Malware Disguises

Thousands have been tricked by a fake ChatGPT Windows client that spreads malware. Learn how these scams work, how to stay safe, and why there’s no official desktop version from OpenAI

Technologies

Understanding Indentation in Python with Examples

How indentation in Python works through simple code examples. This guide explains the structure, spacing, and Python indentation rules every beginner should know