Python datetime Module
Python’s datetime module is a standard library module for handling dates and times. It provides multiple classes and functions to help us easily handle date, time, and time difference operations. Whether it’s getting the current time, formatting dates, or calculating time differences, the datetime module can handle it all.
Core Classes of the datetime Module
Section titled “Core Classes of the datetime Module”The datetime module includes the following core classes:
-
dateclass - Thedateclass represents a date, containing year, month, and day attributes. -
timeclass - Thetimeclass represents a time, containing hour, minute, second, microsecond, and other attributes. -
datetimeclass - Thedatetimeclass is a combination ofdateandtime, allowing simultaneous representation of both date and time. -
timedeltaclass - Thetimedeltaclass represents a time difference and can be used for addition and subtraction operations on dates and times.
Using the datetime Module
Section titled “Using the datetime Module”Getting the Current Date and Time
Section titled “Getting the Current Date and Time”We can use the now() method of the datetime class to get the current date and time.
Example
Section titled “Example”Output example:
Creating a Specific Date and Time
Section titled “Creating a Specific Date and Time”We can create a specific date and time using the constructor of the datetime class.
Example
Section titled “Example”Output example:
Formatting Dates and Times
Section titled “Formatting Dates and Times”datetime objects can be formatted as strings using the strftime() method.
Example
Section titled “Example”Output example:
Calculating Time Differences
Section titled “Calculating Time Differences”The timedelta class can be used to calculate the difference between two dates or times.
Example
Section titled “Example”Output example:
Common Application Scenarios
Section titled “Common Application Scenarios”Calculating the Number of Days Between Two Dates
Section titled “Calculating the Number of Days Between Two Dates”Example
Section titled “Example”Output example:
Handling Time Zones
Section titled “Handling Time Zones”The datetime module itself does not directly support time zone operations, but the pytz library can be used to handle time zones.
Example
Section titled “Example”Output example:
Common Classes, Methods, and Attributes
Section titled “Common Classes, Methods, and Attributes”1. Core Classes
Section titled “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 (includes both date and time) | datetime(2023, 5, 15, 14, 30) |
datetime.timedelta |
Time interval class (for date/time calculations) | timedelta(days=5) |
datetime.tzinfo |
Time zone information base class (requires subclassing) | Custom time zone class |
2. Common Methods/Attributes of the date Object
Section titled “2. Common Methods/Attributes of the date Object”| Method/Attribute | Description | Example |
|---|---|---|
date.today() |
Returns the current local date | date.today() → date(2023, 5, 15) |
date.fromisoformat(str) |
Parses a date from a YYYY-MM-DD 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 day of the week (0=Monday, 6=Sunday) | d.weekday() → 0 |
date.isoformat() |
Returns a 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. Common Methods/Attributes of the time Object
Section titled “3. Common Methods/Attributes of the time 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() |
Returns a HH:MM:SS.mmmmmm format string |
t.isoformat() → "14:30:00" |
time.strftime(format) |
Custom formatted output | t.strftime("%H:%M") → "14:30" |
4. Common Methods/Attributes of the datetime Object
Section titled “4. Common Methods/Attributes of the datetime 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) |
Creates a datetime object from a timestamp |
datetime.fromtimestamp(1684146600) |
datetime.timestamp() |
Returns the timestamp (floating-point 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 as date) |
dt.year → 2023 |
datetime.strftime(format) |
Custom formatted output | dt.strftime("%Y-%m-%d %H:%M") → "2023-05-15 14:30" |
5. Common Attributes of the timedelta Object
Section titled “5. Common Attributes of the timedelta 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)
Section titled “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 |
Examples
Section titled “Examples”1. Calculating Date Difference
Example
Section titled “Example”2. Time Addition and Subtraction
Example
Section titled “Example”3. Time Zone Conversion (requires pytz)
Section titled “3. Time Zone Conversion (requires pytz)”Example
Section titled “Example”4. Parsing Strings
Example
Section titled “Example”Important Notes
Section titled “Important 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: Frequent object creation may affect performance; consider reuse or caching.
-
Boundary Checks: Illegal dates (e.g.,
date(2023, 2, 30)) will trigger aValueError.