Python DateTime Formatting Cheat Sheet

Learn how to parse and format dates and times in Python using datetime, strftime, and strptime.

Core Datetime Classes & Retrieval

Essential classes within the datetime module to capture and instantiate time variables.

MethodSyntaxDescription
datetime.now()datetime.now(tz=None)Returns the current local date and time. Optional timezone info.
datetime.combine()datetime.combine(date, time)Merges distinct date and time objects into a single datetime object.
date()date(year, month, day)Instantiates a timezone-naive date object containing year, month, and day.
time()time(hour, minute, second)Instantiates a timezone-naive time object containing hour, minute, second.
timedelta()timedelta(days=0, seconds=0, weeks=0)Represents a duration expressing the difference between two date or time instances.

Common strftime & strptime Format Codes

Format codes for conversion between datetime objects and formatted strings.

MethodSyntaxDescription
%Y2026Year with century as a decimal number.
%m05Month as a zero-padded decimal number [01, 12].
%d25Day of the month as a zero-padded decimal number [01, 31].
%H23Hour (24-hour clock) as a zero-padded decimal number [00, 23].
%M45Minute as a zero-padded decimal number [00, 59].
%S00Second as a zero-padded decimal number [00, 59].
%AMondayWeekday's full name.
%BMayMonth's full name.

Frequently Asked Questions

What is the difference between strftime and strptime?

strftime (string format time) converts a datetime object into a formatted string. strptime (string parse time) parses a string and converts it into a datetime object.

How do you handle timezone-aware datetimes in Python?

You should use the zoneinfo module (or pytz) and pass a tzinfo parameter to the datetime constructor or call .astimezone(tz).

Keep Learning

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.