Datetime Manipulation
Basic Datetime Operations
Creating Datetime Objects
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
## Create datetime with specific time zone
local_time = datetime.now(ZoneInfo('America/New_York'))
specific_time = datetime(2023, 6, 15, 14, 30, tzinfo=ZoneInfo('UTC'))
Time Calculations
Time Differences and Arithmetic
## Calculate time difference
start_time = datetime(2023, 1, 1, tzinfo=ZoneInfo('UTC'))
end_time = datetime(2023, 12, 31, tzinfo=ZoneInfo('UTC'))
duration = end_time - start_time
print(f"Total days: {duration.days}")
Timedelta Operations
graph LR
A[Original Time] --> B[Add/Subtract Timedelta]
B --> C[New Time]
## Adding and subtracting time
current_time = datetime.now(ZoneInfo('UTC'))
future_time = current_time + timedelta(days=30, hours=5)
past_time = current_time - timedelta(weeks=2)
Time Zone Conversions
Converting Between Time Zones
## Convert between time zones
utc_time = datetime.now(ZoneInfo('UTC'))
tokyo_time = utc_time.astimezone(ZoneInfo('Asia/Tokyo'))
london_time = utc_time.astimezone(ZoneInfo('Europe/London'))
Format |
Description |
Example |
%Y |
4-digit year |
2023 |
%m |
Month |
06 |
%d |
Day |
15 |
%H:%M:%S |
Time |
14:30:00 |
## Formatting datetime
formatted_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
parsed_time = datetime.strptime("2023-06-15 14:30:00", "%Y-%m-%d %H:%M:%S")
Advanced Manipulation
Handling Daylight Saving Time
## DST awareness
dst_time = datetime.now(ZoneInfo('America/New_York'))
is_dst = dst_time.tzinfo.dst(dst_time) != timedelta(0)
print(f"Is Daylight Saving Time: {is_dst}")
LabEx Recommendation
When performing datetime manipulations, always consider time zone context and use standard library methods for consistent results.