Python datetime Module
Python'sdatetimemodule is the standard library module for handling dates and times. It provides several classes and functions that help us easily handle operations such as dates, times, and time differences. Whether it's getting the current time, formatting dates, or calculating time differences,datetimethe module can handle all of these.
Core Classes of the datetime Module
datetimeThe module contains the following core classes:
dateclass -dateThe class is used to represent a date, containing three attributes: year, month, and day.-
timeclass -timeThe class is used to represent a time, containing attributes such as hour, minute, second, and microsecond. -
datetimeclass -datetimeThe class is adateandtimecombination of both, and can represent the date and time simultaneously. -
timedeltaclass -timedeltaThe class is used to represent a time difference and can be used for addition and subtraction operations on dates and times.
Using the datetime Module
Getting Current Date and Time
The class'sdatetimemethodnow()method to get the current date and time.
Example
# Get the current date and time
now = datetime.now()
print("Current time:", now)
Sample output:
当前时间: 2025-04-22 14:30:45.123456
Creating a Specific Date and Time
The class'sdatetimeconstructor to create a specific date and time.
Example
# Create a specific date and time
specific_time = datetime(2025, 4, 22, 15, 30, 0)
print("Specific time:", specific_time)
Sample output:
特定时间: 2025-04-22 15:30:00
Formatting Date and Time
datetimeObjects can bestrftime()formatted into a string by the method.
Example
# Get the current time
now = datetime.now()
# Format the output
formatted_time = now.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted time:", formatted_time)
Sample output:
格式化时间: 2025-04-22 14:30:45
Calculating Time Differences
timedeltaThe class can be used to calculate the difference between two dates or times.
Example
# Get the current time
now = datetime.now()
# Calculate the time 10 days later
future_time = now + timedelta(days=10)
print("Time after 10 days:", future_time)
Sample output:
10 天后的时间: 2025-05-02 14:30:45.123456
Common Use Cases
Calculating the Number of Days Between Two Dates
Example
# Create two dates
date1 = date(2025, 4, 22)
date2 = date(2025, 5, 1)
# Calculate the day difference
delta = date2 - date1
print("Day difference between the two dates:", delta.days)
Sample output:
两个日期之间的天数差: 9
Handling Time Zones
datetimeThe module itself does not directly support time zone operations, but it can be handled through thepytzlibrary to handle time zones.
Example
import pytz
# Get the current time and set the time zone
now = datetime.now(pytz.timezone('Asia/Shanghai'))
print("Current time in Shanghai:", now)
Sample output:
上海当前时间: 2025-04-22 14:30:45.123456+08:00
Common Classes, Methods, and Attributes
1. Core Classes
| Class | Description | Example |
|---|---|---|
datetime.date |
Date class (year, month, day) | date(2023, 5, 15) |
datetime.time |
Time class (hour, minute, second, microsecond) | time(14, 30, 0) |
datetime.datetime |
Datetime class (contains date and time) | datetime(2023, 5, 15, 14, 30) |
datetime.timedelta |
Time interval class (for date/time calculations) | timedelta(days=5) |
datetime.tzinfo |
Timezone info base class (requires subclassing to implement) | Custom timezone class |
2. dateCommon Methods/Attributes of the Object
| Method/Attribute | Description | Example |
|---|---|---|
date.today() |
Returns the current local date | date.today() → date(2023, 5, 15) |
date.fromisoformat(str) |
fromYYYY-MM-DDParses a date from a string |
date.fromisoformat("2023-05-15") |
date.year |
Year (read-only) | d.year → 2023 |
date.month |
Month (1-12, read-only) | d.month → 5 |
date.day |
Day (1-31, read-only) | d.day → 15 |
date.weekday() |
Returns the day of the week (0=Monday, 6=Sunday) | d.weekday() → 0 |
date.isoformat() |
ReturnsYYYY-MM-DDformat string |
d.isoformat() → "2023-05-15" |
date.strftime(format) |
Custom formatted output | d.strftime("%Y/%m/%d") → "2023/05/15" |
3. timeCommon Methods/Attributes of the Object
| Method/Attribute | Description | Example |
|---|---|---|
time.hour |
Hour (0-23, read-only) | t.hour → 14 |
time.minute |
Minute (0-59, read-only) | t.minute → 30 |
time.second |
Second (0-59, read-only) | t.second → 0 |
time.microsecond |
Microsecond (0-999999, read-only) | t.microsecond → 0 |
time.isoformat() |
ReturnsHH:MM:SS.mmmmmmformat string |
t.isoformat() → "14:30:00" |
time.strftime(format) |
Custom formatted output | t.strftime("%H:%M") → "14:30" |
4. datetimeCommon Methods/Attributes of the Object
| Method/Attribute | Description | Example |
|---|---|---|
datetime.now() |
Returns the current local date and time | datetime.now() → datetime(2023, 5, 15, 14, 30, 0) |
datetime.utcnow() |
Returns the current UTC date and time | datetime.utcnow() |
datetime.fromtimestamp(ts) |
Creates from a timestampdatetimeobject |
datetime.fromtimestamp(1684146600) |
datetime.timestamp() |
Returns the timestamp (float seconds) | dt.timestamp() → 1684146600.0 |
datetime.date() |
Extracts the date part | dt.date() → date(2023, 5, 15) |
datetime.time() |
Extracts the time part | dt.time() → time(14, 30) |
datetime.year |
Year (same asdate) |
dt.year → 2023 |
datetime.strftime(format) |
Custom formatted output | dt.strftime("%Y-%m-%d %H:%M") → "2023-05-15 14:30" |
5. timedeltaCommon Attributes of the Object
| Attribute | Description | Example |
|---|---|---|
days |
Days (can be positive or negative) | delta.days → 5 |
seconds |
Seconds (0-86399) | delta.seconds → 3600(1 hour) |
microseconds |
Microseconds (0-999999) | delta.microseconds → 0 |
6. Common Formatting Symbols (strftime)
| Symbol | Description | Example Output |
|---|---|---|
%Y |
Four-digit year | 2023 |
%m |
Two-digit month (01-12) | 05 |
%d |
Two-digit day (01-31) | 15 |
%H |
24-hour hour (00-23) | 14 |
%M |
Minute (00-59) | 30 |
%S |
Second (00-59) | 00 |
%A |
Full weekday name | Monday |
%a |
Abbreviated weekday name | Mon |
%B |
Full month name | May |
%b |
Abbreviated month name | May |
Example
1. Calculate Date Difference
Example
d1 = date(2023, 5, 15)
d2 = date(2023, 6, 1)
delta = d2 - d1 # Returns a timedelta object
print(delta.days) # Output: 17
2. Time Addition and Subtraction
Example
now = datetime.now()
future = now + timedelta(days=3, hours=2)
print(future.strftime("%Y-%m-%d %H:%M"))
3. Time Zone Conversion (requires pytz to be installed)
Example
import pytz
utc_time = datetime.utcnow().replace(tzinfo=pytz.utc)
beijing_time = utc_time.astimezone(pytz.timezone("Asia/Shanghai"))
print(beijing_time)
4. Parsing Strings
Example
dt = datetime.strptime("2023-05-15 14:30", "%Y-%m-%d %H:%M")
print(dt.year) # Output: 2023
Notes
Immutability: All
datetimeobjects are immutable; operations return new objects.Time Zone Handling: Native
datetimehas no time zone support; usepytzor Python 3.9+'szoneinfo。Performance: Frequently creating objects may affect performance; consider reusing or caching.
Boundary Checking: Invalid dates (such as
date(2023, 2, 30)) will triggerValueError。