Working with dates and times looks simple until you start dealing with formats, time zones, daylight saving rules, or timestamps from multiple systems, at which point it's not an option to store time as raw strings or integers. Python’s datetime module exists to help you manage all of these moving parts in a predictable way.
This guide walks through the core classes, how to create and work with datetime objects, how to perform arithmetic, how to format and parse values, handle time zones, and more. Each section builds on the last, so you can move from basic operations to more advanced patterns.
Core Classes of the Python datetime Module
Before doing anything specific, it helps to understand how Python models dates and times at a conceptual level. The datetime module uses a small set of classes, each focused on one part of the problem. Knowing where each class fits makes the rest of the workflow much easier.
date
When you only need a calendar date without worrying about time of day or time zones, the date class is thing you need. It represents the year, month, and day using familiar attributes.
Here are the attributes:
year
month
day
And the methods:
today()
fromisoformat()
replace()
isoformat()
weekday()
isoweekday()
from datetime import date
d = date(2025,3,1)print(d)ขับเคลื่อนโดย
Working with dates and times looks simple until you start dealing with formats, time zones, daylight saving rules, or timestamps from multiple systems, at which point it's not an option to store time as raw strings or integers. Python’s
datetimemodule exists to help you manage all of these moving parts in a predictable way.This guide walks through the core classes, how to create and work with
datetimeobjects, how to perform arithmetic, how to format and parse values, handle time zones, and more. Each section builds on the last, so you can move from basic operations to more advanced patterns.Core Classes of the Python datetime Module
Before doing anything specific, it helps to understand how Python models dates and times at a conceptual level. The
datetimemodule uses a small set of classes, each focused on one part of the problem. Knowing where each class fits makes the rest of the workflow much easier.date
When you only need a calendar date without worrying about time of day or time zones, the
dateclass is thing you need. It represents the year, month, and day using familiar attributes.Here are the attributes:
yearmonthdayAnd the methods:
today()fromisoformat()replace()isoformat()weekday()isoweekday()