Practical Time Techniques
Time Calculations and Manipulations
Working with Time Deltas
from datetime import datetime, timedelta
## Basic time delta operations
current_time = datetime.now()
future_time = current_time + timedelta(days=30)
past_time = current_time - timedelta(weeks=2)
print("Current time:", current_time)
print("30 days from now:", future_time)
print("2 weeks ago:", past_time)
Time Comparison Techniques
## Comparing dates
date1 = datetime(2023, 6, 15)
date2 = datetime(2023, 7, 20)
print("Is date1 earlier?", date1 < date2)
print("Time difference:", date2 - date1)
Time Range Generation
def generate_date_range(start, end, delta):
current = start
while current <= end:
yield current
current += delta
start_date = datetime(2023, 1, 1)
end_date = datetime(2023, 12, 31)
for date in generate_date_range(start_date, end_date, timedelta(days=30)):
print(date.strftime("%Y-%m-%d"))
Timezone Handling
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
## Working with different timezones
local_time = datetime.now()
utc_time = local_time.astimezone(timezone.utc)
tokyo_time = local_time.astimezone(ZoneInfo("Asia/Tokyo"))
print("Local Time:", local_time)
print("UTC Time:", utc_time)
print("Tokyo Time:", tokyo_time)
Time Conversion Workflow
graph TD
A[Local Time] --> B[Convert to UTC]
B --> C[Convert to Target Timezone]
C --> D[Localized Time]
| Technique |
Description |
Example |
| Caching |
Store frequently used time calculations |
@functools.lru_cache |
| Batch Processing |
Process multiple time operations together |
Bulk datetime conversions |
| Lazy Evaluation |
Compute time only when needed |
Generator-based time ranges |
Practical Use Cases
Logging and Timestamps
import logging
from datetime import datetime
def create_timestamped_log():
logging.basicConfig(
filename='app.log',
format='%(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
logging.warning("Application started")
Scheduling and Intervals
import schedule
import time
def job():
print("Executing scheduled task at", datetime.now())
schedule.every(30).minutes.do(job)
while True:
schedule.run_pending()
time.sleep(1)
LabEx Pro Tip
When working with complex time operations, LabEx recommends using libraries like arrow or pendulum for more intuitive time manipulation.
Error Handling in Time Operations
- Always handle potential
ValueError
- Use
try-except for parsing errors
- Validate time inputs before processing
Advanced Time Techniques
- Timestamp to human-readable format
- Time zone conversions
- Handling daylight saving time
- Performance-optimized time calculations