22.Dates & Times
Working with dates and times is essential in many Python applications, from logging events to scheduling tasks. Python provides powerful modules like `datetime` and `time` to handle date and time operations.
Using the datetime Module
The `datetime` module supplies classes for manipulating dates and times. It includes functions to get the current date/time, format dates, and perform arithmetic operations.
Example: Getting Current Date and Time
import datetime
now = datetime.datetime.now()
print(“Current date and time:”, now)
Example: Creating Specific Date
import datetime
d = datetime.datetime(2023, 12, 25)
print(“Christmas Date:”, d)
Example: Formatting Date
now = datetime.datetime.now()
formatted = now.strftime(“%Y-%m-%d %H:%M:%S”)
print(“Formatted date:”, formatted)
Example: Parsing Date String
date_str = “2023-12-25 10:30:00”
parsed_date = datetime.datetime.strptime(date_str, “%Y-%m-%d %H:%M:%S”)
print(“Parsed date:”, parsed_date)
Working with Time Zones
Python’s `datetime` module supports time zones using the `pytz` library. You can convert between time zones and handle daylight saving time.
Example: Time Zone Conversion
import datetime
import pytz
utc = pytz.utc
eastern = pytz.timezone(‘US/Eastern’)
now = datetime.datetime.now(utc)
eastern_time = now.astimezone(eastern)
print(“Eastern Time:”, eastern_time)
Timedelta Operations
`timedelta` objects represent differences between datetime values. You can add or subtract them to compute durations.
Example: Adding Days
import datetime
today = datetime.date.today()
future = today + datetime.timedelta(days=10)
print(“Date after 10 days:”, future)
Using the time Module
The `time` module provides time-related functions such as sleeping and measuring execution time.
Example: Sleep and Time Measurement
Best Practices
- Use `datetime` for date and time manipulation.
- Use `pytz` for accurate time zone handling.
- Avoid using naive datetime objects when working across time zones.
- Use ISO 8601 format for date strings when possible.
- Use `timedelta` for date arithmetic instead of manually calculating time differences.