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.
| Method | Syntax | Description |
|---|---|---|
| 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.
| Method | Syntax | Description |
|---|---|---|
| %Y | 2026 | Year with century as a decimal number. |
| %m | 05 | Month as a zero-padded decimal number [01, 12]. |
| %d | 25 | Day of the month as a zero-padded decimal number [01, 31]. |
| %H | 23 | Hour (24-hour clock) as a zero-padded decimal number [00, 23]. |
| %M | 45 | Minute as a zero-padded decimal number [00, 59]. |
| %S | 00 | Second as a zero-padded decimal number [00, 59]. |
| %A | Monday | Weekday's full name. |
| %B | May | Month'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.
Python Datetime
Learn how to handle dates, times, timezones, and calculations in Python. Master formatting, parsing, and arithmetic using datetime and timedelta.
How to Parse a String to a Datetime in Python
Learn how to convert strings to datetime objects in Python. Master the strptime method, parse date strings, handle timezones, and prevent format errors.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.