Datetime Fundamentals
Introduction to Python Datetime
In Python, datetime manipulation is a crucial skill for handling time-related operations. The datetime
module provides powerful tools for working with dates, times, and time-related calculations.
Core Datetime Classes
Python's datetime module offers several key classes for time representation:
Class |
Description |
Example |
date |
Represents a date (year, month, day) |
date(2023, 6, 15) |
time |
Represents a time (hour, minute, second) |
time(14, 30, 0) |
datetime |
Combines date and time |
datetime(2023, 6, 15, 14, 30) |
timedelta |
Represents a duration of time |
timedelta(days=1) |
Creating Datetime Objects
from datetime import date, time, datetime
## Creating date object
current_date = date.today()
specific_date = date(2023, 6, 15)
## Creating time object
current_time = datetime.now().time()
specific_time = time(14, 30, 0)
## Creating datetime object
current_datetime = datetime.now()
specific_datetime = datetime(2023, 6, 15, 14, 30)
Datetime Attributes and Methods
## Accessing datetime components
dt = datetime.now()
print(dt.year) ## Year
print(dt.month) ## Month
print(dt.day) ## Day
print(dt.hour) ## Hour
print(dt.minute) ## Minute
print(dt.second) ## Second
## String to datetime
date_string = "2023-06-15"
parsed_date = datetime.strptime(date_string, "%Y-%m-%d")
## Datetime to formatted string
formatted_date = datetime.now().strftime("%B %d, %Y")
Datetime Flow Visualization
graph TD
A[Create Datetime Object] --> B{Manipulation Needed?}
B -->|Yes| C[Perform Calculations]
B -->|No| D[Use Datetime Directly]
C --> E[Format or Extract Information]
Best Practices
- Always use
datetime
module for precise time handling
- Be aware of timezone considerations
- Use
strftime()
and strptime()
for consistent parsing and formatting
- Leverage
timedelta
for time arithmetic
By understanding these fundamentals, you'll be well-equipped to handle datetime operations in Python with LabEx's comprehensive learning approach.