Python .strftime()

meleknurb's avatar
Published Jan 9, 2025
Contribute to Docs

The datetime.strftime() method formats time and datetime objects into readable strings on specified format codes.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours

Syntax

datetime.strftime(format)

Here are some commonly used format codes:

Directive Meaning Example
%a Abbreviated name of days Sun, Mon, …, Sat
%d Day of the month 01, 02, …, 31
%b Abbreviated name of months Jan, Feb, …, Dec
%Y Year 0001, 0002, …, 2013, 2014, …, 9998, 9999
%m Month 01, 02, …, 12
%I Hour (12-hour clock) 01, 02, …, 12
%M Minute 00, 01, …, 59
%p Locale’s equivalent of either AM or PM AM, PM

For a complete list, refer to the Python documentation.

Example

The formatted time can be retrieved and stored in a variable as shown in this example:

import datetime
#Assign current time
now = datetime.datetime.now()
#Format the current date and time
formatted_date = now.strftime('%a %d %b %Y, %I:%M%p')
print(formatted_date)

This example results in the following output which displays the current date and time in specific format:

Mon 06 Jan 2025, 09:01PM

Note: The actual output will vary depending on the current date and time when the script is executed.

All contributors

Contribute to Docs

Learn Python on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours