Back to course

Formatting Dates and Times (`strftime` and `strptime`)

Python Programming: The 0 to Hero Bootcamp

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.

CodeMeaningExample
%YFull year2024
%mMonth as a number06
%dDay of the month25
%HHour (24-hour clock)14
%MMinute30
%AFull weekday nameTuesday

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'>