datetime.strftime() / datetime.strptime()
Functions for converting a datetime object to a formatted string, or for creating a datetime object from a formatted string.
Syntax
from datetime import datetime # Converts a datetime object to a formatted string. string = datetime_object.strftime(format_string) # Creates a datetime object from a formatted string. dt = datetime.strptime(string, format_string)
Common Format Codes
| Format Code | Description |
|---|---|
| %Y | 4-digit year (e.g., "2025"). |
| %m | 2-digit month (01–12). |
| %d | 2-digit day (01–31). |
| %H | 2-digit hour in 24-hour format (00–23). |
| %M | 2-digit minute (00–59). |
| %S | 2-digit second (00–59). |
| %A | Full weekday name in English (e.g., "Monday"). |
| %a | Abbreviated weekday name in English (e.g., "Mon"). |
| %B | Full month name in English (e.g., "April"). |
| %b | Abbreviated month name in English (e.g., "Apr"). |
| %I | Hour in 12-hour format (01–12). |
| %p | "AM" or "PM". |
| %f | Microseconds (000000–999999). |
Sample Code
from datetime import datetime
# Display the current datetime in various formats.
now = datetime.now()
# Slash-separated format
print(now.strftime('%Y/%m/%d %H:%M:%S'))
# Example output: '2025/04/15 14:30:00'
# ISO 8601 format
print(now.strftime('%Y-%m-%dT%H:%M:%S'))
# Example output: '2025-04-15T14:30:00'
# Date only (slash-separated)
print(now.strftime('%Y/%m/%d'))
# Example output: '2025/04/15'
# 12-hour format with weekday
print(now.strftime('%Y/%m/%d (%A) %I:%M %p'))
# Example output: '2025/04/15 (Tuesday) 02:30 PM'
# Use strptime() to create a datetime object from a string.
date_str = '2025-04-15 09:30:00'
dt = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S')
print(dt) # Outputs: '2025-04-15 09:30:00'
print(type(dt)) # Outputs: '<class 'datetime.datetime'>'
# Parse a date string in slash-separated format.
date_str2 = '2025/4/15'
dt2 = datetime.strptime(date_str2, '%Y/%m/%d')
print(dt2.year) # Outputs: '2025'
print(dt2.month) # Outputs: '4'
# Convert a date received from a web form.
form_input = '15/04/2025'
dt3 = datetime.strptime(form_input, '%d/%m/%Y')
formatted = dt3.strftime('%Y-%m-%d')
print(formatted) # Outputs: '2025-04-15'
Notes
'strftime()' stands for "string format time" and converts a datetime object to a string in any format you specify. 'strptime()' stands for "string parse time" and creates a datetime object from a formatted string. Both functions use the same format codes, so learning them once lets you use both.
The behavior of some format codes may vary slightly by operating system. For example, the code for removing leading zeros from month or day values ('%-m' on Linux) does not work on Windows. If you need to strip leading zeros, it is more portable to convert the string first and then remove them with 'lstrip("0")'.
For creating datetime objects, see 'datetime.datetime() / datetime.date() / datetime.time()'.
If you find any errors or copyright issues, please contact us.