This article offers 30 Python DateTime practice questions, organized by difficulty. The questions cover the datetime module, basic string formatting, using timedelta for date calculations, working with complex loops, handling month-end cases, and dealing with timezone offsets.
Each coding challenge includes a Practice Problem, Hint, Solution code, and detailed Explanation, ensuring you don’t just copy code, but genuinely practice and understand how and why it works.
- All solutions have been fully tested on Python 3.
- Use our Online Code Editor to solve these exercises in real time.
Let us know if you have any alternative solutions. It will help other developers.
+ Table of Contents (30 Exercises)
Table of contents
- Exercise 1: Print Current Date and Time
- Exercise 2: Format DateTime
- Exercise 3: Find Day of Week
- Exercise 4: Convert Datetime into String
- Exercise 5: Extract Components
- Exercise 6: Print Time with AM/PM
- Exercise 7: Print Current Time in Milliseconds
- Exercise 8: Get the Day of the Year
- Exercise 9: Combine Date and Time Objects
- Exercise 10: Convert String Into Datetime Object
- Exercise 11: Subtract a Week From a Given Date
- Exercise 12: Add Week to Given Date
- Exercise 13: Calculate Days Between Two Dates
- Exercise 14: Convert Unix Timestamp to Datetime
- Exercise 15: Get ISO Week Number
- Exercise 16: Subtract 5 Hours and 30 Minutes
- Exercise 17: Check for Leap Year
- Exercise 18: Calculate Age in Days
- Exercise 19: Difference in Seconds
- Exercise 20: Print a Monthly Calendar
- Exercise 21: Calculate the Date 4 Months From Today
- Exercise 22: Find the First Day of the Month
- Exercise 23: Find the Last Day of the Month
- Exercise 24: Find the Date of the Next Monday
- Exercise 25: Round Time to the Nearest Hour
- Exercise 26: List All Sundays in a Year
- Exercise 27: Calculate Business Days Between Two Dates
- Exercise 28: Convert Local Time to UTC
- Exercise 29: Get Current Time in a Specific City
- Exercise 30: Calculate Date After N Working Days
Exercise 1: Print Current Date and Time
Problem Statement: Write a Python program to print the current date and time.
Purpose: This exercise introduces you to Python’s datetime module and shows how to retrieve the current system date and time – a fundamental skill used in logging, scheduling, and timestamping data.
Given Input: No input required. The program reads the current system date and time.
Expected Output: Current date and time: 2025-01-15 14:23:45.123456 (output will vary based on when the program runs)
Refer: Get Current Date and Time in Python
▼ Solution & Explanation
Explanation:
from datetime import datetime: Imports thedatetimeclass from the built-indatetimemodule. Note that the module and the class share the same name.datetime.now(): Returns the current local date and time as adatetimeobject, including year, month, day, hour, minute, second, and microsecond.print("Current date and time:", now): Displays thedatetimeobject. Python automatically converts it to a readable string in the formatYYYY-MM-DD HH:MM:SS.microseconds.
Exercise 2: Format DateTime
Problem Statement: Write a Python program to format the current date and time into a human-readable string using a custom format.
Purpose: This exercise teaches you how to use strftime() to control the display of date and time values – an essential skill for generating reports, file names, log entries, and user-facing timestamps.
Given Input: No input required. Use the current date and time.
Expected Output: Formatted: 15-Jan-2025 02:23:45 PM (output will vary based on when the program runs)
Refer:
▼ Solution & Explanation
Explanation:
datetime.now(): Retrieves the current local date and time as adatetimeobject.strftime("%d-%b-%Y %I:%M:%S %p"): Converts thedatetimeobject to a formatted string. The format codes are:%dfor zero-padded day,%bfor abbreviated month name,%Yfor full year,%Ifor 12-hour hour,%Mfor minutes,%Sfor seconds, and%pfor AM/PM.print("Formatted:", formatted): Prints the resulting string. Unlike the rawdatetimeobject, this output is fully controlled by your chosen format.
Exercise 3: Find Day of Week
Problem Statement: Write a Python program to find the day of the week for a given date.
Purpose: This exercise shows how to extract the weekday from a date – useful in scheduling applications, calendar tools, and any logic that depends on whether a day falls on a weekday or weekend.
Given Input: date = datetime(2025, 1, 15)
Expected Output: Day of the week: Wednesday
Refer: Python Get the Day of the Week
▼ Solution & Explanation
Explanation:
datetime(2025, 1, 15): Creates adatetimeobject for January 15, 2025. You can substitute any valid year, month, and day values.strftime("%A"): The%Aformat code returns the full name of the weekday for the given date, such asMondayorWednesday.- Alternative:
date.weekday()returns an integer from 0 (Monday) to 6 (Sunday). You can use a list likedays = ["Monday", ..., "Sunday"]and index into it withdays[date.weekday()].
Exercise 4: Convert Datetime into String
Problem Statement: Write a Python program to convert a datetime object into a string representation.
Purpose: This exercise shows how to serialize a datetime object into a plain string, which is needed when storing dates in text files, databases, JSON payloads, or sending them over APIs.
Given Input: dt = datetime(2025, 6, 15, 10, 30, 45)
Expected Output: DateTime as string: 2025-06-15 10:30:45
▼ Solution & Explanation
Explanation:
datetime(2025, 6, 15, 10, 30, 45): Creates adatetimeobject for June 15, 2025 at 10:30:45. The arguments are year, month, day, hour, minute, and second.str(dt): Converts thedatetimeobject to its default string representation in the formatYYYY-MM-DD HH:MM:SS. This is equivalent to callingdt.strftime("%Y-%m-%d %H:%M:%S").- Note: The resulting value is a plain Python string – you can concatenate it, write it to a file, or include it in a JSON object directly.
Exercise 5: Extract Components
Problem Statement: Write a program to extract the Year, Month, Day, Hour, Minute, and Second as separate integers from a single datetime object.
Purpose: This exercise teaches you how to access individual date and time components from a datetime object – useful when you need to perform calculations, comparisons, or conditional logic on specific parts of a timestamp.
Given Input: dt = datetime(2025, 8, 20, 14, 35, 50)
Expected Output: Year: 2025 Month: 8 Day: 20 Hour: 14 Minute: 35 Second: 50
▼ Solution & Explanation
Explanation:
datetime(2025, 8, 20, 14, 35, 50): Creates adatetimeobject representing August 20, 2025 at 14:35:50 (2:35 PM).dt.year,dt.month,dt.day: These attributes return the date portion as separate integers. For example,dt.monthreturns8for August.dt.hour,dt.minute,dt.second: These attributes return the time portion as integers.dt.houruses a 24-hour clock, so14represents 2 PM.
Exercise 6: Print Time with AM/PM
Problem Statement: Format the current time to display in a 12-hour format with AM/PM (e.g., “02:30 PM”).
Purpose: This exercise shows how to present time in the 12-hour clock format that is standard in many user-facing applications, notifications, and interfaces intended for general audiences.
Given Input: No input required. Use the current system time.
Expected Output: Current time: 02:30 PM (output will vary based on when the program runs)
▼ Solution & Explanation
Explanation:
datetime.now(): Returns the current local date and time. Only the time portion is used in this exercise.strftime("%I:%M %p"): Formats the time using 12-hour notation.%Iproduces a zero-padded hour from 01 to 12,%Mproduces zero-padded minutes, and%pappendsAMorPMbased on the hour.- Note: On some platforms,
%pmay produce lowercaseam/pm. If you always want uppercase, use.upper()on the result:now.strftime("%I:%M %p").upper().
Exercise 7: Print Current Time in Milliseconds
Problem Statement: Write a Python program to print the current time including milliseconds.
Purpose: This exercise shows how to access sub-second precision from a datetime object – important in performance profiling, event logging, benchmarking, and any application where millisecond-level accuracy matters.
Given Input: No input required. Use the current system time.
Expected Output: Current time with milliseconds: 14:23:45.123 (output will vary based on when the program runs)
▼ Solution & Explanation
Explanation:
datetime.now(): Captures the current time with microsecond precision. The.microsecondattribute stores a value from 0 to 999999.strftime("%H:%M:%S.%f"): Formats the time with hours, minutes, seconds, and microseconds. The%fcode always produces 6 digits (e.g.,123456).[:-3]: Slices off the last 3 characters from the formatted string, trimming microseconds down to milliseconds. For example,14:23:45.123456becomes14:23:45.123.
Exercise 8: Get the Day of the Year
Problem Statement: Calculate which day of the year it is (from 1 to 366) for any given date.
Purpose: This exercise demonstrates how to derive the ordinal day of the year from a date – a useful calculation in scientific data analysis, day-of-year reporting, agricultural or financial calendars, and countdown timers.
Given Input: date = datetime(2025, 3, 15)
Expected Output: Day of the year: 74
▼ Solution & Explanation
Explanation:
datetime(2025, 3, 15): Creates adatetimeobject for March 15, 2025. January 1 is day 1, and the count continues through December 31 (day 365 or 366 in a leap year).strftime("%j"): Returns the day of the year as a zero-padded 3-character string. For March 15, 2025 it returns"074".int(...): Converts the string"074"to the integer74, removing the leading zero and making the value suitable for arithmetic.
Exercise 9: Combine Date and Time Objects
Problem Statement: Create a date object and a time object separately, then combine them into a single datetime object using datetime.combine().
Purpose: This exercise shows how to work with the date and time types independently before merging them – a pattern commonly used when date and time values arrive from different sources, such as separate form fields or database columns.
Given Input: d = date(2025, 5, 20) and t = time(9, 45, 0)
Expected Output: Combined datetime: 2025-05-20 09:45:00
▼ Solution & Explanation
Explanation:
date(2025, 5, 20): Creates adate-only object representing May 20, 2025. Unlikedatetime, this object holds no time information.time(9, 45, 0): Creates atime-only object representing 9:45:00 AM. The arguments are hour, minute, and second.datetime.combine(d, t): Merges the two objects into a singledatetimeinstance. This is the standard way to assemble a full timestamp when your date and time data come from separate sources.
Exercise 10: Convert String Into Datetime Object
Problem Statement: Write a Python program to convert a date string into a datetime object.
Purpose: This exercise teaches you how to parse date strings using strptime() – a critical skill when reading dates from CSV files, APIs, user input, or databases where dates arrive as plain text and must be converted for calculations or comparisons.
Given Input: date_string = "20 January, 2025"
Expected Output: DateTime object: 2025-01-20 00:00:00
Refer: Python String to DateTime
▼ Solution & Explanation
Explanation:
"20 January, 2025": The input date string. Its structure – day, full month name with a trailing comma, then 4-digit year – must be described precisely in the format argument.datetime.strptime(date_string, "%d %B, %Y"): Parses the string into adatetimeobject.%dmatches the day,%Bmatches the full month name (case-insensitive on most platforms), and%Ymatches the 4-digit year. Since no time is present in the string, the time defaults to00:00:00.- Note:
strptime()is the inverse ofstrftime(). Wherestrftime()converts adatetimeto a string,strptime()converts a string back into adatetime.
Exercise 11: Subtract a Week From a Given Date
Problem Statement: Write a Python program to subtract one week from a given date and print the resulting date.
Purpose: This exercise introduces timedelta, Python’s built-in class for representing a duration or difference between two dates. Subtracting fixed intervals from dates is a common need in scheduling, deadline tracking, and generating historical date ranges.
Given Input: date = datetime(2025, 3, 15)
Expected Output: Date after subtracting one week: 2025-03-08 00:00:00
Refer: TimeDelta in Python
▼ Solution & Explanation
Explanation:
timedelta(weeks=1): Creates a duration object representing exactly 7 days. You can also write this astimedelta(days=7)– both are equivalent.date - one_week: Subtracts the 7-day duration from thedatetimeobject. Python’sdatetimearithmetic handles month and year boundaries automatically, so subtracting a week from March 3rd correctly produces February 24th.result: Holds a brand-newdatetimeobject. The originaldatevariable is unchanged, asdatetimeobjects are immutable in Python.
Exercise 12: Add Week to Given Date
Problem Statement: Write a Python program to add one week to a given date and print the resulting date.
Purpose: This exercise reinforces the use of timedelta for forward date arithmetic – a pattern used frequently in reminder systems, subscription renewals, appointment scheduling, and expiry date calculations.
Given Input: date = datetime(2025, 3, 15)
Expected Output: Date after adding one week: 2025-03-22 00:00:00
Refer: TimeDelta in Python
▼ Solution & Explanation
Explanation:
timedelta(weeks=1): Represents a fixed duration of 7 days. Thetimedeltaclass also acceptsdays,hours,minutes,seconds, andmicrosecondsas arguments, which can be combined freely (e.g.,timedelta(weeks=1, hours=3)).date + one_week: Adds the 7-day duration to thedatetimeobject. Python handles rollovers across month and year boundaries automatically, so adding a week to March 28th correctly produces April 4th.result: A newdatetimeobject set to March 22, 2025. The originaldatevariable is unchanged.
Exercise 13: Calculate Days Between Two Dates
Problem Statement: Write a Python program to calculate the number of days between two given dates.
Purpose: This exercise shows how to measure the elapsed time between two points in time – a calculation needed in age computations, project duration tracking, invoice due-date checks, and any feature that works with date ranges.
Given Input: date1 = datetime(2025, 1, 1) and date2 = datetime(2025, 3, 15)
Expected Output: Days between dates: 73
Refer: Python Difference Between Two Dates in Days.
▼ Solution & Explanation
Explanation:
date2 - date1: Subtracting twodatetimeobjects returns atimedeltaobject representing the duration between them. No import oftimedeltais needed here since you are reading the result, not constructing one.delta.days: The.daysattribute of atimedeltagives the total whole-day count as an integer. For this example, the 73 days from January 1 to March 15 span across two months and are calculated automatically.- Note: A
timedeltaalso has.secondsand.microsecondsattributes for sub-day precision. To get the total duration in seconds, usedelta.total_seconds()instead.
Exercise 14: Convert Unix Timestamp to Datetime
Problem Statement: Given a Unix timestamp (e.g., 1672531200), convert it into a human-readable Python datetime object.
Purpose: This exercise shows how to interpret Unix timestamps, which are integers representing the number of seconds elapsed since January 1, 1970 (UTC). They appear throughout APIs, server logs, databases, and file systems, making this conversion an essential real-world skill.
Given Input: timestamp = 1672531200
Expected Output: Datetime from timestamp: 2023-01-01 00:00:00
▼ Solution & Explanation
Explanation:
1672531200: A Unix timestamp representing the number of seconds that have passed since the Unix epoch: January 1, 1970 at 00:00:00 UTC. This particular value corresponds to January 1, 2023 at midnight UTC.datetime.utcfromtimestamp(timestamp): Converts the integer into adatetimeobject expressed in UTC. This is the safest choice when the source of the timestamp is a server or API that stores times in UTC, as it avoids any local timezone offset being applied.- Alternative:
datetime.fromtimestamp(timestamp)converts to your local system time instead of UTC. The output will differ depending on the timezone of the machine running the code, so preferutcfromtimestamp()for portable, consistent results.
Exercise 15: Get ISO Week Number
Problem Statement: Find the ISO week number for a specific date (e.g., January 1st, 2026).
Purpose: This exercise introduces the ISO 8601 week numbering system, where weeks run Monday to Sunday and the first week of the year is defined as the week containing the first Thursday. ISO week numbers are widely used in business reporting, payroll systems, and European calendar conventions.
Given Input: date = datetime(2026, 1, 1)
Expected Output: ISO week number: 1
▼ Solution & Explanation
Explanation:
datetime(2026, 1, 1): Creates adatetimeobject for January 1, 2026. Under the ISO 8601 standard, this date falls on a Thursday, which means it belongs to week 1 of 2026.strftime("%V"): Returns the ISO 8601 week number as a zero-padded 2-character string.%Valways counts weeks starting on Monday, and week 1 is defined as the week that contains the first Thursday of the year.- Alternative:
date.isocalendar()returns a named tuple with three fields. You can access the week number directly withdate.isocalendar().week, which already returns an integer and makes the intent of the code clearer.
Exercise 16: Subtract 5 Hours and 30 Minutes
Problem Statement: Take the current time and subtract exactly 5 hours and 30 minutes from it using timedelta.
Purpose: This exercise helps you practice using timedelta for time arithmetic, a skill essential in scheduling, time zone conversions, and log analysis where offsets from a reference time are commonly needed.
Given Input: Current datetime (e.g., datetime.now())
Expected Output: 5 hours and 30 minutes before now: 2025-07-15 08:45:00.123456 (actual value will vary)
▼ Solution & Explanation
Explanation:
timedelta(hours=5, minutes=30): Creates a duration object representing 5 hours and 30 minutes.timedeltaaccepts keyword arguments likedays,hours,minutes, andseconds.now - delta: Subtracts the duration from the current datetime. Python’sdatetimesupports arithmetic withtimedeltadirectly using-and+operators.- Use case: This pattern is commonly used to compute “N hours ago” timestamps for filtering logs, displaying relative times, or adjusting for time zone differences.
Exercise 17: Check for Leap Year
Problem Statement: Write a function that takes a year as input and returns True if it is a leap year and False otherwise, using the calendar module.
Purpose: This exercise introduces the calendar module and Boolean-returning functions, while reinforcing the concept of leap year logic used in date calculations, calendar applications, and scheduling systems.
Given Input: year = 2024
Expected Output: 2024 is a leap year: True
▼ Solution & Explanation
Explanation:
calendar.isleap(year): A built-in function from thecalendarmodule that returnsTrueif the given year is a leap year. A year is a leap year if it is divisible by 4, except for century years, which must be divisible by 400.def is_leap_year(year): Wrapping the logic in a named function makes it reusable and testable across multiple inputs.- Alternative: You could implement the leap year logic manually with
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0), butcalendar.isleap()is cleaner and less error-prone.
Exercise 18: Calculate Age in Days
Problem Statement: Input a birthdate and calculate exactly how many days old a person is today.
Purpose: This exercise practices date subtraction and working with timedelta objects, skills used in age verification systems, health apps, and any application that needs to measure elapsed time between two dates.
Given Input: birthdate = date(1995, 6, 15)
Expected Output: Age in days: 10992 (actual value will vary based on today’s date)
▼ Solution & Explanation
Explanation:
date.today(): Returns the current local date as adateobject (without time). It is preferred overdatetime.now().date()when only the date portion is needed.today - birthdate: Subtracting twodateobjects produces atimedeltaobject representing the difference..days: Thetimedeltaattribute that returns the total number of whole days in the duration as an integer.
Exercise 19: Difference in Seconds
Problem Statement: Calculate the total number of seconds between two specific datetime objects.
Purpose: This exercise teaches you to extract the total elapsed time in seconds from a timedelta, a technique used in performance benchmarking, event duration tracking, and countdown timers.
Given Input: dt1 = datetime(2025, 1, 1, 9, 0, 0) and dt2 = datetime(2025, 1, 1, 11, 45, 30)
Expected Output: Difference in seconds: 9930.0
▼ Solution & Explanation
Explanation:
dt2 - dt1: Subtracting twodatetimeobjects yields atimedeltarepresenting the gap between them. Ensure the later datetime is on the left to avoid a negative result..total_seconds(): Returns the total duration expressed purely in seconds as a float, combining days, seconds, and microseconds into a single value. This is more reliable than accessing.secondsalone, which only covers the seconds component within the final day.- Verification: 2 hours and 45 minutes and 30 seconds equals
(2 * 3600) + (45 * 60) + 30 = 9930seconds, confirming the output.
Exercise 20: Print a Monthly Calendar
Problem Statement: Accept a year and a month from the user and print a formatted text calendar for that month.
Purpose: This exercise introduces the calendar module’s text rendering capabilities, useful for building CLI tools, report generators, and any interface that needs to display human-readable date grids.
Given Input: year = 2025, month = 7
Expected Output:
July 2025
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
▼ Solution & Explanation
Explanation:
int(input(...)): Reads the year and month as strings from the user and converts them to integers, which is required by thecalendarfunctions.calendar.month(year, month): Returns a multi-line string containing a nicely formatted text calendar for the specified month and year, with the week starting on Monday by default.- Alternative: Use
calendar.prmonth(year, month)to print the calendar directly without needing an explicitprint()call.
Exercise 21: Calculate the Date 4 Months From Today
Problem Statement: Calculate and display the date that falls exactly 4 months from the current date.
Purpose: This exercise teaches month-based date arithmetic, a common requirement in billing cycles, subscription renewals, and project deadline calculations where timedelta alone is insufficient because months vary in length.
Given Input: Current date (e.g., date.today())
Expected Output: Date 4 months from today: 2025-11-15 (actual value will vary)
▼ Solution & Explanation
Explanation:
month = today.month - 1 + months_to_add: Converts the month to a zero-based index before adding, which makes the modulo arithmetic for wrapping around December work correctly.year = today.year + month // 12: Increments the year whenever the total months exceed 12 (e.g., adding 4 months to October results in February of the next year).calendar.monthrange(year, month)[1]: Returns the number of days in the target month, used to clamp the day and avoid invalid dates like February 31.today.replace(...): Creates a newdateobject with updated year, month, and day fields while leaving unspecified fields unchanged.
Exercise 22: Find the First Day of the Month
Problem Statement: For any given date, write a script to find the date of the first day of that specific month.
Purpose: This exercise practices date manipulation with replace(), commonly used in financial reporting, monthly aggregations, and generating date ranges that start at the beginning of a billing or calendar period.
Given Input: given_date = date(2025, 8, 17)
Expected Output: First day of the month: 2025-08-01
▼ Solution & Explanation
Explanation:
given_date.replace(day=1): Returns a newdateobject with the same year and month as the original, but with the day set to 1. Thereplace()method never modifies the original object sincedateobjects are immutable.- Practical use: This one-liner is a standard pattern in data pipelines for grouping records by month, e.g.,
transaction_date.replace(day=1)normalizes any date to its month bucket.
Exercise 23: Find the Last Day of the Month
Problem Statement: Determine the last day of the current month (e.g., 28, 29, 30, or 31).
Purpose: This exercise shows how to query month-end dates using the calendar module, a requirement in payroll systems, invoice due-date calculations, and any logic that must handle months of varying lengths including leap year Februaries.
Given Input: Current date (e.g., date.today())
Expected Output: Last day of current month: 2025-07-31 (actual value will vary)
▼ Solution & Explanation
Explanation:
calendar.monthrange(year, month): Returns a two-element tuple. The first element is the integer weekday of the first day of the month (0 = Monday), and the second is the total number of days in that month. This automatically accounts for leap years.[1]: Indexes into the tuple to extract only the day count (e.g., 28, 29, 30, or 31).today.replace(day=last_day_num): Builds a completedateobject for the last day of the current month by replacing only the day component.
Exercise 24: Find the Date of the Next Monday
Problem Statement: Write a script that calculates the date of the upcoming Monday, regardless of what today’s date is.
Purpose: This exercise practices weekday arithmetic using timedelta and weekday(), skills used in scheduling tools, weekly report generators, and calendar applications that need to align dates to specific days of the week.
Given Input: Current date (e.g., date.today())
Expected Output: Next Monday: 2025-07-21 (actual value will vary)
▼ Solution & Explanation
Explanation:
today.weekday(): Returns the current day as an integer from 0 (Monday) to 6 (Sunday). For example, Wednesday returns 2.(7 - today.weekday()) % 7: Calculates how many days remain until the next Monday. The modulo by 7 ensures that if today is already Monday (weekday() == 0), the result is 0 rather than 7.if days_ahead == 0: days_ahead = 7: Handles the edge case where today is Monday. Without this check, the script would return today’s date rather than next Monday.timedelta(days=days_ahead): Adds the computed offset to today to land precisely on the next Monday.
Exercise 25: Round Time to the Nearest Hour
Problem Statement: Write a program that takes a datetime object and rounds it to the closest full hour.
Purpose: This exercise practices minute-based time arithmetic and conditional rounding logic, techniques applied in time series analysis, billing rounded to the nearest hour, and event logging systems that bucket timestamps.
Given Input: dt = datetime(2025, 7, 15, 14, 35, 0)
Expected Output: Rounded to nearest hour: 2025-07-15 15:00:00
▼ Solution & Explanation
Explanation:
dt.minute >= 30: The rounding condition. If the minutes are at least 30, the time is closer to the next hour, so it rounds up; otherwise it rounds down to the current hour.dt + timedelta(hours=1): Advances the datetime by one hour before zeroing out the sub-hour components. This correctly handles edge cases like rounding 23:45 up to midnight (00:00 the next day)..replace(minute=0, second=0, microsecond=0): Strips all sub-hour components from the datetime object, leaving a clean on-the-hour timestamp.- Example breakdown: The input
14:35has 35 minutes, which is greater than or equal to 30, so it rounds up to15:00.
Exercise 26: List All Sundays in a Year
Problem Statement: Generate a list of all dates that fall on a Sunday for the year 2026.
Purpose: This exercise practices iterating over a date range and filtering by weekday, a technique used in scheduling systems, retail planning, and any application that needs to enumerate specific days across a calendar year.
Given Input: year = 2026
Expected Output: A list of all 52 Sunday dates in 2026, starting with 2026-01-04 and ending with 2026-12-27.
▼ Solution & Explanation
Explanation:
current.weekday() != 6: Advances day by day from January 1st until the first Sunday is found. In Python’sweekday()system, 0 is Monday and 6 is Sunday.timedelta(weeks=1): Once the first Sunday is located, stepping by exactly 7 days each iteration guarantees every subsequent date also lands on a Sunday, making the loop far more efficient than checking every single day.sundays.append(current): Builds the list incrementally. The result can be used for further processing, such as filtering events or generating weekly report dates.- Result: Most years contain 52 Sundays. Years where January 1st falls on a Sunday, or leap years starting on Saturday, will have 53.
Exercise 27: Calculate Business Days Between Two Dates
Problem Statement: Calculate the number of days between two dates, excluding Saturdays and Sundays.
Purpose: This exercise teaches weekday filtering over a date range, an essential skill in HR systems, project management tools, SLA tracking, and financial applications where only working days count toward deadlines.
Given Input: start = date(2025, 7, 1) and end = date(2025, 7, 31)
Expected Output: Business days between 2025-07-01 and 2025-07-31: 23
▼ Solution & Explanation
Explanation:
current.weekday() < 5: A concise condition that matches only weekdays. Sinceweekday()returns 0 (Monday) through 6 (Sunday), any value less than 5 is a working day. Values 5 and 6 (Saturday and Sunday) are automatically skipped.while current < end: Uses a strict less-than comparison so the end date itself is not counted, consistent with the common convention of counting days between two dates exclusively.- Alternative – NumPy:
numpy.busday_count(start, end)achieves the same result in a single call and also supports custom holiday arrays for more advanced business day calculations. - Note: This solution does not account for public holidays. To exclude them, maintain a list of holiday dates and add
and current not in holidaysto the condition.
Exercise 28: Convert Local Time to UTC
Problem Statement: Take a local datetime object and convert it to Coordinated Universal Time (UTC).
Purpose: This exercise introduces timezone-aware datetime objects and UTC conversion, a foundational skill for building globally distributed applications, APIs, databases, and any system that stores or transmits timestamps across time zones.
Given Input: A naive local datetime representing IST (UTC+5:30), e.g., datetime(2025, 7, 15, 10, 30, 0)
Expected Output: Local (IST): 2025-07-15 10:30:00+05:30 and UTC: 2025-07-15 05:00:00+00:00
▼ Solution & Explanation
Explanation:
ZoneInfo("Asia/Kolkata"): Creates a timezone object for Indian Standard Time (UTC+5:30) using the IANA timezone database.zoneinfois part of the standard library from Python 3.9 onwards, so no third-party installation is required.naive_dt.replace(tzinfo=...): Stamps the timezone onto a naive (timezone-unaware)datetimewithout changing the time value. Use this only when you know the datetime was originally created in that specific zone..astimezone(ZoneInfo("UTC")): Converts the aware datetime to the target timezone, recalculating the time value accordingly. Here, 10:30 IST becomes 05:00 UTC because IST is 5 hours and 30 minutes ahead of UTC.- Alternative: For Python versions below 3.9, use the
pytzlibrary:pytz.timezone("Asia/Kolkata").localize(naive_dt)followed by.astimezone(pytz.utc).
Exercise 29: Get Current Time in a Specific City
Problem Statement: Use the zoneinfo (or pytz) library to print the current time in “Asia/Tokyo” and “America/New_York”.
Purpose: This exercise demonstrates how to retrieve and display the current time across multiple time zones simultaneously, a core requirement in world clocks, international meeting schedulers, trading dashboards, and global customer support tools.
Given Input: No input required. Uses datetime.now() with a timezone argument.
Expected Output: Current times in both cities, formatted clearly (actual values will vary by when the program is run).
See: Working With TimeZones in Python
▼ Solution & Explanation
Explanation:
datetime.now(tz=ZoneInfo(tz_name)): Returns the current moment expressed in the specified timezone. This is the preferred approach over converting from UTC after the fact, and it correctly handles Daylight Saving Time transitions automatically.- Dictionary of timezones: Storing city-to-IANA-zone mappings in a dictionary makes the code easy to extend. Adding more cities requires only a new key-value pair, with no changes to the loop logic.
strftime("%Z"): Appends the timezone abbreviation (e.g.,JSTorEDT) to the output string, making it immediately clear which zone each timestamp belongs to.- Alternative – pytz: Replace
ZoneInfo(tz_name)withpytz.timezone(tz_name)for compatibility with Python versions below 3.9. The rest of the code remains unchanged.
Exercise 30: Calculate Date After N Working Days
Problem Statement: Given a start date, find the date that occurs after 10 working days, skipping weekends.
Purpose: This exercise combines weekday checking with iterative date advancement, a pattern used in contract management, delivery estimation, legal deadline calculators, and any workflow where turnaround times are measured in business days rather than calendar days.
Given Input: start_date = date(2025, 7, 1) and n = 10
Expected Output: Date after 10 working days from 2025-07-01: 2025-07-15
▼ Solution & Explanation
Explanation:
current += timedelta(days=1)before the check: The day is advanced first, then evaluated. This ensures the start date itself is never counted as one of the working days, which matches the real-world convention of “N working days from today.”current.weekday() < 5: Counts only weekdays (Monday through Friday). Saturday (5) and Sunday (6) are stepped over without incrementing the counter, so the loop naturally absorbs weekends.- Encapsulated as a function: Wrapping the logic in
add_working_days(start_date, n)makes it reusable for any start date and any number of working days, not just the specific example. - Extension: To also skip public holidays, pass a
holidaysset to the function and addand current not in holidaysto the counting condition.

I would like to want how to do below exercise. Could you tell me the answer.
Write a program that asks the user for the current hour and for how many hours in the future they want to go.
Have the program print out what the hour will be that many hours in the future. For instance, if it’s 13 o’clock now, 27 hours from now it will be 16 o’clock
Thanks for your help and your good web site.
An alternative method for day difference:
Is my code correct for Ex-7?
Ex – 10:
hai can any one tell how to calculate interest rate with with start date to present date…. like for example start date 2020/5/15(YY/MM/DD) to today date…. and given money 10000.and rate of interest 5…. so please tell me how to calculate?????????
Here’s my solution for #7.
Exercise 10:
Ex-5
Error – # to get weekday as integer
# this will give today date
I think it should be
print(given_date.weekday())I would like to want how to do below exercise. Could you tell me the answer.
Write a program that asks the user for the current hour and for how many hours in the future they want to go.
Have the program print out what the hour will be that many hours in the future. For instance, if it’s 13 o’clock now, 27 hours from now it will be 16 o’clock
Thanks for your help and your good web site.
This might be the solution-