How to Format Date in Python: Simple Guide with Examples
In Python, you can format dates using the
strftime method from the datetime module. This method converts a date object into a string based on format codes like %Y for year or %m for month.Syntax
The basic syntax to format a date in Python is:
date_object.strftime(format_string): Converts the date object to a string based on the given format.format_string: A string containing special codes that represent parts of the date like year, month, day, hour, etc.
Common format codes include:
%Y: 4-digit year (e.g., 2024)%m: 2-digit month (01-12)%d: 2-digit day (01-31)%H: 24-hour (00-23)%M: minutes (00-59)%S: seconds (00-59)
python
from datetime import datetime now = datetime.now() formatted_date = now.strftime("%Y-%m-%d %H:%M:%S") print(formatted_date)
Output
2024-06-15 14:30:45
Example
This example shows how to get the current date and time, then format it as a readable string like "2024-06-15 14:30:45".
python
from datetime import datetime # Get current date and time now = datetime.now() # Format date as Year-Month-Day Hour:Minute:Second formatted_date = now.strftime("%Y-%m-%d %H:%M:%S") print("Formatted date:", formatted_date)
Output
Formatted date: 2024-06-15 14:30:45
Common Pitfalls
Some common mistakes when formatting dates in Python include:
- Using incorrect format codes (e.g.,
%Mfor month instead of%m). - Trying to format a string instead of a
datetimeobject. - Not importing the
datetimemodule before using it.
Always check the format codes carefully and ensure you are working with a datetime object.
python
from datetime import datetime now = datetime.now() # Wrong: Using %M for month (actually minutes) wrong_format = now.strftime("%Y-%M-%d") print("Wrong format:", wrong_format) # Right: Use %m for month right_format = now.strftime("%Y-%m-%d") print("Right format:", right_format)
Output
Wrong format: 2024-30-15
Right format: 2024-06-15
Quick Reference
| Format Code | Meaning | Example |
|---|---|---|
| %Y | 4-digit year | 2024 |
| %m | 2-digit month | 06 |
| %d | 2-digit day | 15 |
| %H | 24-hour clock | 14 |
| %M | Minutes | 30 |
| %S | Seconds | 45 |
| %a | Abbreviated weekday | Mon |
| %A | Full weekday name | Monday |
| %b | Abbreviated month name | Jun |
| %B | Full month name | June |
Key Takeaways
Use datetime objects with the strftime method to format dates in Python.
Remember that format codes like %Y, %m, and %d represent year, month, and day respectively.
Avoid mixing up format codes such as %M (minutes) and %m (month).
Always import the datetime module before formatting dates.
Test your format strings to ensure the output matches your expectations.