Datetime Operations
Creating Datetime Objects
from datetime import datetime, date, timedelta
## Creating datetime objects
current_datetime = datetime.now()
specific_date = datetime(2023, 6, 15, 14, 30, 0)
today = date.today()
Datetime Arithmetic
## Date calculations
future_date = current_datetime + timedelta(days=30)
past_date = current_datetime - timedelta(weeks=2)
## Time differences
time_difference = future_date - current_datetime
print(f"Days until future date: {time_difference.days}")
## String to datetime conversion
date_string = "2023-06-15"
parsed_date = datetime.strptime(date_string, "%Y-%m-%d")
## Datetime to string formatting
formatted_date = current_datetime.strftime("%B %d, %Y")
print(f"Formatted date: {formatted_date}")
Common Datetime Methods
Method |
Description |
Example |
replace() |
Modify specific components |
new_date = current_datetime.replace(year=2024) |
weekday() |
Get day of the week |
day_number = current_datetime.weekday() |
timestamp() |
Convert to timestamp |
time_stamp = current_datetime.timestamp() |
Datetime Comparison
## Comparing dates
date1 = datetime(2023, 6, 15)
date2 = datetime(2023, 7, 20)
print(f"Is date1 earlier? {date1 < date2}")
print(f"Are dates equal? {date1 == date2}")
Datetime Manipulation Flow
graph TD
A[Datetime Object] --> B[Create]
A --> C[Modify]
A --> D[Compare]
A --> E[Format]
B --> F[From Current Time]
B --> G[From Specific Values]
C --> H[Add/Subtract Time]
C --> I[Replace Components]
D --> J[Comparison Operators]
E --> K[To String]
E --> L[From String]
Advanced Datetime Techniques
- Handling complex date calculations
- Working with time intervals
- Performance optimization
LabEx Insights
At LabEx, we emphasize the importance of mastering datetime operations for robust Python programming, enabling precise time manipulation and analysis.
Error Handling
try:
## Datetime operations
invalid_date = datetime(2023, 13, 32)
except ValueError as e:
print(f"Invalid date: {e}")
Best Practices
- Use
datetime
for complex time operations
- Be cautious with timezone-naive datetime objects
- Utilize
timedelta
for date arithmetic
- Handle potential exceptions in datetime conversions