Solutions
Exercise 1: Basic Date & Time Creation and Display Solutions
from datetime import date, datetime
# 1. Current Date and Time:
current_datetime = datetime.now()
print(f"1. Current Date and Time: {current_datetime}")
# 2. Current Date Only:
current_date = date.today()
print(f"2. Current Date Only: {current_date}")
# 3. Specific Date (Your Birthday Example):
# Replace with your actual birthday
my_birthday = date(1990, 5, 15)
print(f"3. My Birthday: {my_birthday}")
# 4. Specific Datetime:
specific_datetime = datetime(2025, 1, 1, 10, 30, 0)
print(f"4. Specific Datetime: {specific_datetime}")
# 5. Formatted Output (YYYY-MM-DD HH:MM:SS):
formatted_current_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
print(f"5. Formatted Current Datetime: {formatted_current_datetime}")
# 6. Custom Format (Day, Month DD, YYYY):
formatted_birthday = my_birthday.strftime("%A, %B %d, %Y")
print(f"6. Formatted Birthday: {formatted_birthday}")
Exercise 2: Parsing Dates from Strings Solutions
from datetime import date, datetime
# 1. Basic Parsing:
date_str_1 = "2023-03-15"
parsed_date_1 = datetime.strptime(date_str_1, "%Y-%m-%d").date()
print(f"1. Parsed Date '2023-03-15': {parsed_date_1}")
# 2. Datetime Parsing:
datetime_str_2 = "2024-07-22 14:30:00"
parsed_datetime_2 = datetime.strptime(datetime_str_2, "%Y-%m-%d %H:%M:%S")
print(f"2. Parsed Datetime '2024-07-22 14:30:00': {parsed_datetime_2}")
# 3. Mixed Format:
datetime_str_3 = "Dec 25, 2023 10:00 PM"
parsed_datetime_3 = datetime.strptime(datetime_str_3, "%b %d, %Y %I:%M %p")
print(f"3. Parsed Datetime 'Dec 25, 2023 10:00 PM': {parsed_datetime_3}")
# 4. ISO Format:
# datetime.fromisoformat() is convenient for ISO 8601
iso_str_4 = "2023-11-01T09:00:00"
parsed_iso_datetime_4 = datetime.fromisoformat(iso_str_4)
print(f"4. Parsed ISO Datetime '2023-11-01T09:00:00': {parsed_iso_datetime_4}")
Exercise 3: Date Arithmetic (Timedelta) Solutions
from datetime import date, datetime, timedelta
# Get today's date and current datetime for calculations
today = date.today()
now = datetime.now()
# 1. Future Date (7 days from today):
future_date = today + timedelta(days=7)
print(f"1. Date 7 days from today: {future_date}")
# 2. Past Date (3 weeks ago from today):
past_date = today - timedelta(weeks=3)
print(f"2. Date 3 weeks ago: {past_date}")
# 3. Future Time (5 hours and 30 minutes from now):
future_time = now + timedelta(hours=5, minutes=30)
print(f"3. Time 5 hours 30 minutes from now: {future_time.strftime('%Y-%m-%d %H:
%M:%S')}")
# 4. Date Difference:
date1 = date(2023, 1, 1)
date2 = date(2023, 12, 31)
diff_days = (date2 - date1).days
print(f"4. Number of days between {date1} and {date2}: {diff_days} days")
# 5. Age Calculation (in days):
# Replace with your actual birthday
my_birthday = date(1990, 5, 15)
age_in_days = (today - my_birthday).days
print(f"5. My age in days: {age_in_days} days")
Exercise 4: Weekdays and Calendars Solutions
from datetime import date
import calendar
# 1. Day of the Week:
target_date = date(2023, 10, 27)
day_of_week = target_date.strftime("%A") # %A gives full weekday name
print(f"1. {target_date} was a: {day_of_week}")
# 2. Is it a Weekend?
def is_weekend(d_obj):
# weekday() returns 0 for Monday, 6 for Sunday
return d_obj.weekday() >= 5
test_weekday = date(2023, 10, 27) # Friday
test_weekend_sat = date(2023, 10, 28) # Saturday
test_weekend_sun = date(2023, 10, 29) # Sunday
print(f"2. Is {test_weekday} a weekend? {is_weekend(test_weekday)}")
print(f" Is {test_weekend_sat} a weekend? {is_weekend(test_weekend_sat)}")
print(f" Is {test_weekend_sun} a weekend? {is_weekend(test_weekend_sun)}")
# 3. Leap Year Check:
def is_leap_year(year):
return calendar.isleap(year)
print(f"3. Is 2024 a leap year? {is_leap_year(2024)}") # True
print(f" Is 2023 a leap year? {is_leap_year(2023)}") # False
print(f" Is 2000 a leap year? {is_leap_year(2000)}") # True (divisible by 400)
print(f" Is 1900 a leap year? {is_leap_year(1900)}") # False (divisible by 100 but not
400)
Exercise 5: Time Zones (Advanced) Solutions
Note: You might need to install pytz: pip install pytz
from datetime import datetime
import pytz # Requires: pip install pytz
# 1. Current UTC Time:
utc_now = datetime.now(pytz.utc)
print(f"1. Current UTC Time: {utc_now}")
# 2. Local Time in Specific Timezone:
new_york_tz = pytz.timezone("America/New_York")
ny_now = datetime.now(new_york_tz)
print(f"2. Current Time in New York: {ny_now}")
# 3. Convert Timezone:
kolkata_tz = pytz.timezone("Asia/Kolkata")
# Convert the UTC time obtained earlier to Kolkata time
kolkata_time = utc_now.astimezone(kolkata_tz)
print(f"3. UTC Time converted to Asia/Kolkata: {kolkata_time}")
# 4. Naive to Aware:
naive_dt = datetime(2024, 7, 22, 10, 0, 0) # A naive datetime object
london_tz = pytz.timezone("Europe/London")
# Make the naive datetime aware by localizing it to London timezone
aware_dt_london = london_tz.localize(naive_dt)
print(f"4. Naive datetime: {naive_dt}")
print(f" Aware datetime in London: {aware_dt_london}")
# You can also convert this aware datetime to another timezone
# paris_tz = pytz.timezone("Europe/Paris")
# aware_dt_paris = aware_dt_london.astimezone(paris_tz)
# print(f" Aware datetime in Paris: {aware_dt_paris}")