.strftime()
Published Jan 9, 2025
Contribute to Docs
The datetime.strftime()
method formats time and datetime
objects into readable strings on specified format codes.
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 timenow = datetime.datetime.now()#Format the current date and timeformatted_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.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours