Date and Time Formatting
Dates and times are often stored internally as objects but need to be displayed to users in a readable format.
1. Formatting Objects to Strings (strftime)
strftime (String Format Time) converts a datetime object into a custom formatted string.
| Code | Meaning | Example |
|---|---|---|
%Y | Full year | 2024 |
%m | Month as a number | 06 |
%d | Day of the month | 25 |
%H | Hour (24-hour clock) | 14 |
%M | Minute | 30 |
%A | Full weekday name | Tuesday |
python from datetime import datetime
current = datetime.now()
formatted_date = current.strftime("Today is %A, %B %d, %Y") print(formatted_date)
Output: Today is Tuesday, June 25, 2024
formatted_time = current.strftime("Time: %H:%M:%S") print(formatted_time)
2. Parsing Strings to Objects (strptime)
strptime (String Parse Time) takes a formatted string and converts it back into a datetime object. You must provide the exact format string used.
python date_string = "15-05-2025" format_code = "%d-%m-%Y"
Converts the string to a datetime object
present_date = datetime.strptime(date_string, format_code) print(present_date) print(type(present_date)) # <class 'datetime.datetime'>