PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » Python Exercises » Python Date and Time Exercises: 30 Coding Problems with Solutions

Python Date and Time Exercises: 30 Coding Problems with Solutions

Updated on: April 20, 2026 | 10 Comments

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
from datetime import datetime

now = datetime.now()
print("Current date and time:", now)Code language: Python (python)

Explanation:

  • from datetime import datetime: Imports the datetime class from the built-in datetime module. Note that the module and the class share the same name.
  • datetime.now(): Returns the current local date and time as a datetime object, including year, month, day, hour, minute, second, and microsecond.
  • print("Current date and time:", now): Displays the datetime object. Python automatically converts it to a readable string in the format YYYY-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: 

  • Python DateTime Format Using Strftime()
  • Date format codes
▼ Solution & Explanation
from datetime import datetime

now = datetime.now()
formatted = now.strftime("%d-%b-%Y %I:%M:%S %p")
print("Formatted:", formatted)Code language: Python (python)

Explanation:

  • datetime.now(): Retrieves the current local date and time as a datetime object.
  • strftime("%d-%b-%Y %I:%M:%S %p"): Converts the datetime object to a formatted string. The format codes are: %d for zero-padded day, %b for abbreviated month name, %Y for full year, %I for 12-hour hour, %M for minutes, %S for seconds, and %p for AM/PM.
  • print("Formatted:", formatted): Prints the resulting string. Unlike the raw datetime object, 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
from datetime import datetime

date = datetime(2025, 1, 15)
day_name = date.strftime("%A")
print("Day of the week:", day_name)Code language: Python (python)

Explanation:

  • datetime(2025, 1, 15): Creates a datetime object for January 15, 2025. You can substitute any valid year, month, and day values.
  • strftime("%A"): The %A format code returns the full name of the weekday for the given date, such as Monday or Wednesday.
  • Alternative: date.weekday() returns an integer from 0 (Monday) to 6 (Sunday). You can use a list like days = ["Monday", ..., "Sunday"] and index into it with days[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
from datetime import datetime

dt = datetime(2025, 6, 15, 10, 30, 45)
dt_string = str(dt)
print("DateTime as string:", dt_string)Code language: Python (python)

Explanation:

  • datetime(2025, 6, 15, 10, 30, 45): Creates a datetime object for June 15, 2025 at 10:30:45. The arguments are year, month, day, hour, minute, and second.
  • str(dt): Converts the datetime object to its default string representation in the format YYYY-MM-DD HH:MM:SS. This is equivalent to calling dt.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
from datetime import datetime

dt = datetime(2025, 8, 20, 14, 35, 50)

print("Year:", dt.year)
print("Month:", dt.month)
print("Day:", dt.day)
print("Hour:", dt.hour)
print("Minute:", dt.minute)
print("Second:", dt.second)Code language: Python (python)

Explanation:

  • datetime(2025, 8, 20, 14, 35, 50): Creates a datetime object 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.month returns 8 for August.
  • dt.hour, dt.minute, dt.second: These attributes return the time portion as integers. dt.hour uses a 24-hour clock, so 14 represents 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
from datetime import datetime

now = datetime.now()
time_ampm = now.strftime("%I:%M %p")
print("Current time:", time_ampm)Code language: Python (python)

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. %I produces a zero-padded hour from 01 to 12, %M produces zero-padded minutes, and %p appends AM or PM based on the hour.
  • Note: On some platforms, %p may produce lowercase am/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
from datetime import datetime

now = datetime.now()
time_ms = now.strftime("%H:%M:%S.%f")[:-3]
print("Current time with milliseconds:", time_ms)Code language: Python (python)

Explanation:

  • datetime.now(): Captures the current time with microsecond precision. The .microsecond attribute stores a value from 0 to 999999.
  • strftime("%H:%M:%S.%f"): Formats the time with hours, minutes, seconds, and microseconds. The %f code 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.123456 becomes 14: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
from datetime import datetime

date = datetime(2025, 3, 15)
day_of_year = int(date.strftime("%j"))
print("Day of the year:", day_of_year)Code language: Python (python)

Explanation:

  • datetime(2025, 3, 15): Creates a datetime object 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 integer 74, 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
from datetime import date, time, datetime

d = date(2025, 5, 20)
t = time(9, 45, 0)
combined = datetime.combine(d, t)
print("Combined datetime:", combined)Code language: Python (python)

Explanation:

  • date(2025, 5, 20): Creates a date-only object representing May 20, 2025. Unlike datetime, this object holds no time information.
  • time(9, 45, 0): Creates a time-only object representing 9:45:00 AM. The arguments are hour, minute, and second.
  • datetime.combine(d, t): Merges the two objects into a single datetime instance. 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
from datetime import datetime

date_string = "20 January, 2025"
dt = datetime.strptime(date_string, "%d %B, %Y")
print("DateTime object:", dt)Code language: Python (python)

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 a datetime object. %d matches the day, %B matches the full month name (case-insensitive on most platforms), and %Y matches the 4-digit year. Since no time is present in the string, the time defaults to 00:00:00.
  • Note: strptime() is the inverse of strftime(). Where strftime() converts a datetime to a string, strptime() converts a string back into a datetime.

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
from datetime import datetime, timedelta

date = datetime(2025, 3, 15)
one_week = timedelta(weeks=1)
result = date - one_week

print("Date after subtracting one week:", result)Code language: Python (python)

Explanation:

  • timedelta(weeks=1): Creates a duration object representing exactly 7 days. You can also write this as timedelta(days=7) – both are equivalent.
  • date - one_week: Subtracts the 7-day duration from the datetime object. Python’s datetime arithmetic handles month and year boundaries automatically, so subtracting a week from March 3rd correctly produces February 24th.
  • result: Holds a brand-new datetime object. The original date variable is unchanged, as datetime objects 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
from datetime import datetime, timedelta

date = datetime(2025, 3, 15)
one_week = timedelta(weeks=1)
result = date + one_week

print("Date after adding one week:", result)Code language: Python (python)

Explanation:

  • timedelta(weeks=1): Represents a fixed duration of 7 days. The timedelta class also accepts days, hours, minutes, seconds, and microseconds as arguments, which can be combined freely (e.g., timedelta(weeks=1, hours=3)).
  • date + one_week: Adds the 7-day duration to the datetime object. Python handles rollovers across month and year boundaries automatically, so adding a week to March 28th correctly produces April 4th.
  • result: A new datetime object set to March 22, 2025. The original date variable 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
from datetime import datetime

date1 = datetime(2025, 1, 1)
date2 = datetime(2025, 3, 15)
delta = date2 - date1

print("Days between dates:", delta.days)Code language: Python (python)

Explanation:

  • date2 - date1: Subtracting two datetime objects returns a timedelta object representing the duration between them. No import of timedelta is needed here since you are reading the result, not constructing one.
  • delta.days: The .days attribute of a timedelta gives 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 timedelta also has .seconds and .microseconds attributes for sub-day precision. To get the total duration in seconds, use delta.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
from datetime import datetime

timestamp = 1672531200
dt = datetime.utcfromtimestamp(timestamp)

print("Datetime from timestamp:", dt)Code language: Python (python)

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 a datetime object 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 prefer utcfromtimestamp() 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
from datetime import datetime

date = datetime(2026, 1, 1)
iso_week = int(date.strftime("%V"))

print("ISO week number:", iso_week)Code language: Python (python)

Explanation:

  • datetime(2026, 1, 1): Creates a datetime object 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. %V always 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 with date.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
from datetime import datetime, timedelta

now = datetime.now()
delta = timedelta(hours=5, minutes=30)
result = now - delta

print("5 hours and 30 minutes before now:", result)Code language: Python (python)

Explanation:

  • timedelta(hours=5, minutes=30): Creates a duration object representing 5 hours and 30 minutes. timedelta accepts keyword arguments like days, hours, minutes, and seconds.
  • now - delta: Subtracts the duration from the current datetime. Python’s datetime supports arithmetic with timedelta directly 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
import calendar

def is_leap_year(year):
    return calendar.isleap(year)

year = 2024
print(f"{year} is a leap year: {is_leap_year(year)}")Code language: Python (python)

Explanation:

  • calendar.isleap(year): A built-in function from the calendar module that returns True if 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), but calendar.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
from datetime import date

birthdate = date(1995, 6, 15)
today = date.today()
age_in_days = (today - birthdate).days

print("Age in days:", age_in_days)Code language: Python (python)

Explanation:

  • date.today(): Returns the current local date as a date object (without time). It is preferred over datetime.now().date() when only the date portion is needed.
  • today - birthdate: Subtracting two date objects produces a timedelta object representing the difference.
  • .days: The timedelta attribute 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
from datetime import datetime

dt1 = datetime(2025, 1, 1, 9, 0, 0)
dt2 = datetime(2025, 1, 1, 11, 45, 30)

diff = dt2 - dt1
print("Difference in seconds:", diff.total_seconds())Code language: Python (python)

Explanation:

  • dt2 - dt1: Subtracting two datetime objects yields a timedelta representing 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 .seconds alone, 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 = 9930 seconds, 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
import calendar

year = int(input("Enter year: "))
month = int(input("Enter month (1-12): "))

print(calendar.month(year, month))Code language: Python (python)

Explanation:

  • int(input(...)): Reads the year and month as strings from the user and converts them to integers, which is required by the calendar functions.
  • 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 explicit print() 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
from datetime import date
import calendar

today = date.today()
months_to_add = 4

month = today.month - 1 + months_to_add
year = today.year + month // 12
month = month % 12 + 1

max_day = calendar.monthrange(year, month)[1]
day = min(today.day, max_day)

future_date = today.replace(year=year, month=month, day=day)
print("Date 4 months from today:", future_date)Code language: Python (python)

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 new date object 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
from datetime import date

given_date = date(2025, 8, 17)
first_day = given_date.replace(day=1)

print("First day of the month:", first_day)Code language: Python (python)

Explanation:

  • given_date.replace(day=1): Returns a new date object with the same year and month as the original, but with the day set to 1. The replace() method never modifies the original object since date objects 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
from datetime import date
import calendar

today = date.today()
last_day_num = calendar.monthrange(today.year, today.month)[1]
last_day = today.replace(day=last_day_num)

print("Last day of current month:", last_day)Code language: Python (python)

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 complete date object 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
from datetime import date, timedelta

today = date.today()
days_ahead = (7 - today.weekday()) % 7
if days_ahead == 0:
    days_ahead = 7

next_monday = today + timedelta(days=days_ahead)
print("Next Monday:", next_monday)Code language: Python (python)

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
from datetime import datetime, timedelta

dt = datetime(2025, 7, 15, 14, 35, 0)

if dt.minute >= 30:
    rounded = (dt + timedelta(hours=1)).replace(minute=0, second=0, microsecond=0)
else:
    rounded = dt.replace(minute=0, second=0, microsecond=0)

print("Rounded to nearest hour:", rounded)Code language: Python (python)

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:35 has 35 minutes, which is greater than or equal to 30, so it rounds up to 15: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
from datetime import date, timedelta
year = 2026
sundays = []
current = date(year, 1, 1)
end = date(year, 12, 31)
# Advance to the first Sunday of the year
while current.weekday() != 6:
    current += timedelta(days=1)
# Collect all Sundays by stepping 7 days at a time
while current <= end:
    sundays.append(current)
    current += timedelta(weeks=1)
print(f"Total Sundays in {year}: {len(sundays)}")
for sunday in sundays:
    print(sunday)Code language: Python (python)

Explanation:

  • current.weekday() != 6: Advances day by day from January 1st until the first Sunday is found. In Python’s weekday() 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
from datetime import date, timedelta
start = date(2025, 7, 1)
end = date(2025, 7, 31)
business_days = 0
current = start
while current < end:
    if current.weekday() < 5:  # 0=Monday ... 4=Friday
        business_days += 1
    current += timedelta(days=1)
print(f"Business days between {start} and {end}: {business_days}")Code language: Python (python)

Explanation:

  • current.weekday() < 5: A concise condition that matches only weekdays. Since weekday() 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 holidays to 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
from datetime import datetime
from zoneinfo import ZoneInfo

# Naive datetime representing a local time in IST (UTC+5:30)
naive_dt = datetime(2025, 7, 15, 10, 30, 0)

# Make it timezone-aware by attaching the local timezone
local_dt = naive_dt.replace(tzinfo=ZoneInfo("Asia/Kolkata"))

# Convert to UTC
utc_dt = local_dt.astimezone(ZoneInfo("UTC"))

print("Local (IST):", local_dt)
print("UTC:        ", utc_dt)Code language: Python (python)

Explanation:

  • ZoneInfo("Asia/Kolkata"): Creates a timezone object for Indian Standard Time (UTC+5:30) using the IANA timezone database. zoneinfo is 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) datetime without 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 pytz library: 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
from datetime import datetime
from zoneinfo import ZoneInfo

timezones = {
    "Tokyo":    "Asia/Tokyo",
    "New York": "America/New_York",
}

for city, tz_name in timezones.items():
    current_time = datetime.now(tz=ZoneInfo(tz_name))
    formatted = current_time.strftime("%Y-%m-%d %H:%M:%S %Z")
    print(f"Current time in {city}: {formatted}")Code language: Python (python)

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., JST or EDT) to the output string, making it immediately clear which zone each timestamp belongs to.
  • Alternative – pytz: Replace ZoneInfo(tz_name) with pytz.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
from datetime import date, timedelta
def add_working_days(start_date, n):
    current = start_date
    working_days_counted = 0
    while working_days_counted < n:
        current += timedelta(days=1)
        if current.weekday() < 5:  # Monday to Friday
            working_days_counted += 1
    return current
start_date = date(2025, 7, 1)
n = 10
result = add_working_days(start_date, n)
print(f"Date after {n} working days from {start_date}: {result}")Code language: Python (python)

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 holidays set to the function and add and current not in holidays to the counting condition.

深圳市网捷达科技有限公司 联系电话:18910898173;

ICP备案号:粤ICP备2024312167号-2

Copyright © 网捷达 版权所有

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Exercises

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Comments

  1. subbareddy says

    September 27, 2023 at 8:48 pm

    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.

    Reply
  2. anonymous says

    June 9, 2022 at 8:18 pm

    An alternative method for day difference:

    import datetime
    
    # 2020-02-25
    date_1 = datetime.datetime(2020, 2, 25)
    
    # 2020-09-17
    date_2 = datetime.datetime(2020, 9, 17)
    
    date_difference = abs(date_1 - date_2)
    
    print(date_difference.days)
    Reply
  3. Divya says

    March 11, 2022 at 7:42 pm

    Is my code correct for Ex-7?

    from datetime import *
    
    current_time = datetime.now()
    micro_sec = (current_time.strftime('%f'))
    # %f--> Microsecond
    # 1 microsecond = 0.001 milliseconds
    
    milli_sec = (int(micro_sec)/1000)
    print(milli_sec)
    Reply
  4. Florin says

    November 22, 2021 at 7:11 pm

    Ex – 10:

    date_1 = datetime(2020, 2, 25)
    
    date_2 = datetime(2020, 9, 17)
    days = date_2 - date_1
    
    print((days.days),"days")
    Reply
  5. M vinodkumar says

    September 27, 2021 at 12:40 pm

    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?????????

    Reply
  6. AndyLee says

    July 4, 2021 at 6:16 am

    Here’s my solution for #7.

    import datetime
    ms = datetime.datetime.now().timestamp() * 1000
    print(ms)
    Reply
  7. Mounir El-Abbas says

    June 18, 2021 at 12:28 am

    Exercise 10:

    
    import datetime
    
    # 2020-02-25
    date_1 = datetime.datetime(2020, 2, 25)
    
    # 2020-09-17
    date_2 = datetime.datetime(2020, 9, 17)
    
    day_diff = date_1 - date_2
    print(abs(day_diff))
    
    Reply
  8. DMS KARUNARATNE says

    September 16, 2020 at 4:21 pm

    Ex-5
    Error – # to get weekday as integer

    print(given_date.today().weekday())

    # this will give today date

    I think it should be print(given_date.weekday())

    Reply
    • New Learner says

      May 25, 2021 at 11:00 am

      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.

      Reply
      • Divya says

        March 11, 2022 at 8:20 pm

        This might be the solution-

        from datetime import *
        
        current_time = datetime.now()
        x = int(input('How long(in hours) you want to go in future: '))
        after_hr = current_time + timedelta(hours=x)
        print(after_hr)
        Reply

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python Python Exercises
TweetF  sharein  shareP  Pin

  Python Exercises

  • All Python Exercises
  • Basic Exercise for Beginners
  • Intermediate Python Exercises
  • Input and Output Exercise
  • Loop Exercise
  • Functions Exercise
  • String Exercise
  • Data Structure Exercise
  • List Exercise
  • Dictionary Exercise
  • Set Exercise
  • Tuple Exercise
  • Date and Time Exercise
  • OOP Exercise
  • File Handling Exercise
  • Python JSON Exercise
  • Random Data Generation Exercise
  • NumPy Exercise
  • Pandas Exercise
  • Matplotlib Exercise
  • Python Database Exercise

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com

深圳市网捷达科技有限公司 联系电话:18910898173;

ICP备案号:粤ICP备2024312167号-2

Copyright © 网捷达 版权所有