Last modified: May 04, 2026 By Alexander Williams
Python Datetime Format Guide
Working with dates and times is common in many Python projects. The datetime module helps you handle them easily. But formatting dates for display or parsing strings into dates can be tricky. This guide covers everything you need to know about Python datetime format.
We will focus on two key methods: strftime and strptime. These let you convert between datetime objects and strings. We will also show examples and outputs. By the end, you will format dates like a pro.
What is Python Datetime Format?
Python datetime format refers to how you represent date and time data as strings. The datetime module provides classes like datetime, date, time, and timedelta. To format them, you use special format codes.
Format codes are placeholders. For example, %Y represents the full year. %m represents the month. These codes let you create custom date strings.
If you need to get the current date and time first, read our guide on Python datetime now: Get Current Date & Time. It shows how to get the starting point for formatting.
Using strftime to Format Datetime
The strftime method converts a datetime object into a string. It stands for "string format time". You pass a format string with codes. The method returns a formatted string.
Here is the basic syntax:
from datetime import datetime
# Get current datetime
now = datetime.now()
# Format as YYYY-MM-DD
formatted = now.strftime("%Y-%m-%d")
print(formatted)
2025-03-21
Let's try more examples. You can combine different codes.
from datetime import datetime
now = datetime.now()
# Full date and time
formatted1 = now.strftime("%A, %B %d, %Y at %I:%M %p")
print(formatted1)
# 24-hour format
formatted2 = now.strftime("%d/%m/%Y %H:%M:%S")
print(formatted2)
# Just time
formatted3 = now.strftime("%H:%M:%S")
print(formatted3)
Friday, March 21, 2025 at 02:30 PM
21/03/2025 14:30:45
14:30:45
Important: The %I gives 12-hour clock. %H gives 24-hour clock. Use %p for AM/PM.
Common Format Codes
Here is a list of the most used format codes:
%Y- Year with century (e.g., 2025)%y- Year without century (e.g., 25)%m- Month as zero-padded number (01-12)%B- Full month name (e.g., March)%b- Abbreviated month name (e.g., Mar)%d- Day of month (01-31)%A- Full weekday name (e.g., Friday)%a- Abbreviated weekday name (e.g., Fri)%H- Hour (00-23)%I- Hour (01-12)%M- Minute (00-59)%S- Second (00-59)%p- AM or PM
You can also use %f for microseconds. Practice these codes to build any format you need.
Using strptime to Parse Strings
The strptime method does the opposite. It parses a string into a datetime object. It stands for "string parse time". You provide the string and a format string that matches it.
Here is the syntax:
from datetime import datetime
# Parse a date string
date_string = "2025-03-21 14:30:45"
parsed_date = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(parsed_date)
print(type(parsed_date))
2025-03-21 14:30:45
<class 'datetime.datetime'>
Notice the format string must match the string exactly. If they don't match, Python raises a ValueError. Be careful with spaces and punctuation.
Another example with a different format:
from datetime import datetime
# Parse a string with month name
date_string = "March 21, 2025"
parsed_date = datetime.strptime(date_string, "%B %d, %Y")
print(parsed_date)
2025-03-21 00:00:00
When you parse only a date, time defaults to midnight.
Formatting Time Zones
By default, datetime objects are naive (no time zone). To format with time zone, use %z for UTC offset or %Z for time zone name. First, you need a timezone-aware datetime.
Here is an example using pytz:
from datetime import datetime
import pytz
# Create timezone-aware datetime
tz = pytz.timezone("US/Eastern")
now_ny = datetime.now(tz)
# Format with timezone
formatted = now_ny.strftime("%Y-%m-%d %H:%M:%S %Z")
print(formatted)
2025-03-21 09:30:45 EDT
Important: %Z gives the time zone abbreviation. %z gives the offset like -0400. This is useful for logs and international apps.
Working with Date Only or Time Only
The datetime module also has date and time classes. They work similarly.
Here is how to format a date object:
from datetime import date
today = date.today()
formatted = today.strftime("%A, %B %d, %Y")
print(formatted)
Friday, March 21, 2025
And for a time object:
from datetime import time
t = time(14, 30, 45)
formatted = t.strftime("%I:%M %p")
print(formatted)
02:30 PM
These methods are consistent across all datetime classes.
Common Pitfalls and Tips
Beginners often make mistakes with format codes. Here are tips to avoid errors.
Tip 1: Always match the format string exactly in strptime. A single extra space causes an error.
Tip 2: Use %m for month number and %M for minute. They look similar but are different. This is a common typo.
Tip 3: For two-digit years, use %y. Python assumes 1969-2068 for %y. Use %Y for clarity.
Tip 4: Locale affects month and weekday names. If you need a specific language, set the locale first with locale.setlocale().
For a deeper understanding of the datetime module, check our Master Python Datetime Guide. It covers all classes and advanced topics.
Practical Example: Log Formatter
Let's build a simple log formatter. This shows how to use format in real code.
from datetime import datetime
def log_message(message):
"""Log a message with timestamp."""
now = datetime.now()
timestamp = now.strftime("%Y-%m-%d %H:%M:%S")
log_entry = f"[{timestamp}] {message}"
print(log_entry)
log_message("User logged in")
log_message("File saved successfully")
[2025-03-21 14:30:45] User logged in
[2025-03-21 14:30:46] File saved successfully
This pattern is common in applications. You can extend it to write to files.
Conclusion
Python datetime format is powerful and easy to use. The strftime method converts datetime objects to strings. The strptime method parses strings into datetime objects. Use format codes like %Y, %m, %d to build custom formats.
Remember to match format strings exactly when parsing. Watch out for common mistakes like mixing %m and %M. Practice with different codes to become confident.
Now you can format dates for reports, logs, or user interfaces. Start using these methods in your projects today.