Combining and Manipulating Dates and Times
Once you have a solid understanding of the date and time data structures in Python, you can start combining and manipulating them to perform various operations. This section will cover the common techniques and methods for working with dates and times in Python.
Combining Dates and Times
In Python, you can combine dates and times using the datetime class. Here's an example:
from datetime import datetime, date, time
## Combine a date and a time
date_obj = date(2023, 4, 15)
time_obj = time(15, 30, 0)
datetime_obj = datetime.combine(date_obj, time_obj)
print(datetime_obj) ## Output: 2023-04-15 15:30:00
You can also create a datetime object directly from a string representation:
datetime_obj = datetime.strptime("2023-04-15 15:30:00", "%Y-%m-%d %H:%M:%S")
print(datetime_obj) ## Output: 2023-04-15 15:30:00
Manipulating Dates and Times
Python's datetime module provides various methods and operations for manipulating dates and times, such as:
- Extracting components (year, month, day, hour, minute, second)
- Performing arithmetic operations (addition, subtraction, comparison)
- Calculating time differences and durations
- Formatting and parsing date and time strings
Here's an example of manipulating a datetime object:
from datetime import datetime, timedelta
## Create a datetime object
dt = datetime(2023, 4, 15, 15, 30, 0)
## Add 2 days and 3 hours
new_dt = dt + timedelta(days=2, hours=3)
print(new_dt) ## Output: 2023-04-17 18:30:00
## Calculate the time difference
time_diff = new_dt - dt
print(time_diff) ## Output: 2 days, 3:00:00
Time Zone Conversions
Python's datetime module also provides support for working with time zones. You can use the pytz library to handle time zone conversions:
import pytz
from datetime import datetime
## Create a datetime object in UTC
utc_dt = datetime(2023, 4, 15, 15, 30, 0, tzinfo=pytz.utc)
## Convert to a different time zone
eastern_tz = pytz.timezone('US/Eastern')
eastern_dt = utc_dt.astimezone(eastern_tz)
print(eastern_dt) ## Output: 2023-04-15 11:30:00-04:00
By understanding these techniques for combining and manipulating dates and times, you can build powerful applications that handle complex date and time-related requirements.