Practical Date Manipulation Examples
Now that you have a solid understanding of working with dates and times in Python, let's explore some practical examples of date manipulation.
Calculating Age
One common use case is calculating a person's age based on their date of birth. Here's an example:
from datetime import date
def calculate_age(birth_date):
today = date.today()
age = today.year - birth_date.year
if today.month < birth_date.month or (today.month == birth_date.month and today.day < birth_date.day):
age -= 1
return age
birth_date = date(1990, 5, 15)
age = calculate_age(birth_date)
print(f"The person's age is: {age}") ## Output: The person's age is: 33
Generating a Date Range
Another common task is generating a range of dates, such as for a report or a calendar. You can use the timedelta
class to achieve this:
from datetime import date, timedelta
def generate_date_range(start_date, end_date):
date_range = []
current_date = start_date
while current_date <= end_date:
date_range.append(current_date)
current_date += timedelta(days=1)
return date_range
start_date = date(2023, 4, 15)
end_date = date(2023, 4, 20)
date_range = generate_date_range(start_date, end_date)
print(date_range)
## Output: [datetime.date(2023, 4, 15), datetime.date(2023, 4, 16), datetime.date(2023, 4, 17), datetime.date(2023, 4, 18), datetime.date(2023, 4, 19), datetime.date(2023, 4, 20)]
Handling Timezones
When working with dates and times, it's important to consider timezones, especially in applications that deal with users or data from different locations. The dateutil
module can help with this:
from datetime import datetime
from dateutil import tz
## Convert a datetime object to a different timezone
dt = datetime(2023, 4, 15, 10, 30, 0)
utc_dt = dt.replace(tzinfo=tz.UTC)
local_dt = utc_dt.astimezone(tz.gettz('America/New_York'))
print(local_dt) ## Output: 2023-04-15 06:30:00-04:00
By understanding these practical examples, you can apply your knowledge of date and time manipulation to a wide range of real-world scenarios in your Python applications.