ข้ามไปยังเนื้อหาหลัก

Python datetime: How to Work with Dates and Times in Python

Learn the different ways to work with Python’s datetime tools and simplify everything from parsing strings to managing timezone-aware timestamps.
· 2 นาที อ่าน

สำรวจด้วย AI

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)