Python datetime Module
Python's datetime module is the standard library module for handling dates and times. It provides various classes and functions that make it easy to work with dates, times and time differences. Whether getting the current time, formatting dates or computing time differences, thedatetime module can handle it.
Core classes of the datetime module
datetime module contains the following core classes:
-
dateClass -dateclass represents a date and has three attributes: year, month and day. -
timeClass -timeclass represents a time and has attributes such as hour, minute, second and microsecond. -
datetimeClass -datetimeThe class isdateandtimecombined, representing both date and time. -
timedeltaClass -timedeltaclass represents a time difference and can be used for date and time arithmetic.
Using the datetime module
Get the current date and time
We can use the datetime The class's now() method to get the current date and time.
Example
from
datetime
import
datetime
Get the current date and time
now
=
datetime
.
now
(
)
(
"Current time:"
,
now
)
Example output:
当前时间: 2025-04-22 14:30:45.123456
Create a specific date and time
We can use datetime class constructor to create a specific date and time.
Example
from
datetime
import
datetime
Create a specific date and time
specific_time
=
datetime
(
2025
,
4
,
22
,
15
,
30
,
0
)
(
"Specific time:"
,
specific_time
)
Example output:
特定时间: 2025-04-22 15:30:00
Formatting dates and times
datetime object can be formatted into a string with the strftime() method.
Example
from
datetime
import
datetime
Get the current time
now
=
datetime
.
now
(
)
Formatted output
formatted_time
=
now.
strftime
(
"%Y-%m-%d %H:%M:%S"
)
(
"Formatted time:"
,
formatted_time
)
Example output:
格式化时间: 2025-04-22 14:30:45
Compute a time difference
timedelta class can compute the difference between two dates or times.
Example
from
datetime
import
datetime
,
timedelta
Get the current time
now
=
datetime
.
now
(
)
Compute the time 10 days from now
future_time
=
now + timedelta
(
days
=
10
)
(
"Time 10 days later:"
,
future_time
)
Example output:
10 天后的时间: 2025-05-02 14:30:45.123456
Common Application Scenarios
Compute the number of days between two dates
Example
from
datetime
import
date
Create two dates
date1
=
date
(
2025
,
4
,
22
)
date2
=
date
(
2025
,
5
,
1
)
Compute the difference in days
delta
=
date2 - date1
(
"Difference in days between the two dates:"
,
delta.
days
)
Example output:
两个日期之间的天数差: 9
Handling time zones
datetime module does not directly support time zone operations, but this can be done with the pytz library.
Example
from
datetime
import
datetime
import
pytz
Get the current time and set the time zone
now
=
datetime
.
now
(
pytz.
timezone
(
'Asia/Shanghai'
)
)
(
"Current time in Shanghai:"
,
now
)
Example 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 (containing date and time) | datetime(2023, 5, 15, 14, 30) |
datetime.timedelta |
Time interval class (for date/time calculations) | timedelta(days=5) |
datetime.tzinfo |
Timezone information base class (requires subclassing) | Custom timezone class |
2. date Common 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) |
From the YYYY-MM-DD Parse 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() |
Return YYYY-MM-DD Format string |
d.isoformat() → "2023-05-15" |
date.strftime(format) |
Custom formatted output | d.strftime("%Y/%m/%d") → "2023/05/15" |
3. time Common 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() |
Return HH:MM:SS.mmmmmm Format string |
t.isoformat() → "14:30:00" |
time.strftime(format) |
Custom formatted output | t.strftime("%H:%M") → "14:30" |
4. datetime Common methods/attributes of the object
| Method/attribute | Description | Example |
|---|---|---|
datetime.now() |
Returns the current local datetime | datetime.now() → datetime(2023, 5, 15, 14, 30, 0) |
datetime.utcnow() |
Returns the current UTC datetime | datetime.utcnow() |
datetime.fromtimestamp(ts) |
Create from a timestamp datetime object |
datetime.fromtimestamp(1684146600) |
datetime.timestamp() |
Returns the timestamp (float seconds) | dt.timestamp() → 1684146600.0 |
datetime.date() |
Extract the date part | dt.date() → date(2023, 5, 15) |
datetime.time() |
Extract the time part | dt.time() → time(14, 30) |
datetime.year |
Year (same as date) |
dt.year → 2023 |
datetime.strftime(format) |
Custom formatted output | dt.strftime("%Y-%m-%d %H:%M") → "2023-05-15 14:30" |
5. timedelta Common attributes of the object
| property | Description | Example |
|---|---|---|
days |
Number of 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 format symbols (strftime)
| sign before positive numbers | Description | Example output |
|---|---|---|
%Y |
Four-digit year | 2023 |
%m |
Two-digit month (01-12) | 05 |
%d |
Two-digit day (01-31) | 15 |
%H |
Hour in 24-hour format (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
- Compute the date difference
Example
from
datetime
import
date
,
timedelta
d1
=
date
(
2023
,
5
,
15
)
d2
=
date
(
2023
,
6
,
1
)
delta
=
d2 - d1
Returns a timedelta object
(
delta.
days
)
Output: 17
- Time addition and subtraction
Example
from
datetime
import
datetime
,
timedelta
now
=
datetime
.
now
(
)
future
=
now + timedelta
(
days
=
3
,
hours
=
2
)
(
future.
strftime
(
"%Y-%m-%d %H:%M"
)
)
3. Timezone conversion (requires pytz)
Example
from
datetime
import
datetime
import
pytz
utc_time
=
datetime
.
utcnow
(
)
.
replace
(
tzinfo
=
pytz.
utc
)
beijing_time
=
utc_time.
astimezone
(
pytz.
timezone
(
"Asia/Shanghai"
)
)
(
beijing_time
)
- Parse a string
Example
from
datetime
import
datetime
dt
=
datetime
.
strptime
(
"2023-05-15 14:30"
,
"%Y-%m-%d %H:%M"
)
(
dt.
year
)
Output: 2023
Notes
-
Immutability: all
datetimeObjects are immutable; operations return a new object. -
Timezone handling: native
datetime: no timezone support; you need to usepytzor Python 3.9+'szoneinfo。 -
Performance: frequently creating objects may affect performance; consider reusing or caching.
-
bounds checking: invalid dates (such as
date(2023, 2, 30)) will triggerValueError。