Bird
Raised Fist0
Pythonprogramming~20 mins

Date and time handling in Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
DateTime Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of datetime timedelta addition
What is the output of this Python code snippet?
Python
from datetime import datetime, timedelta

start = datetime(2024, 6, 15, 12, 0, 0)
delta = timedelta(days=3, hours=4, minutes=30)
result = start + delta
print(result.strftime('%Y-%m-%d %H:%M:%S'))
A2024-06-18 16:30:00
B2024-06-18 04:30:00
C2024-06-19 16:30:00
D2024-06-15 16:30:00
Attempts:
2 left
💡 Hint
Add days, then hours and minutes to the start datetime.
Predict Output
intermediate
2:00remaining
Output of datetime string parsing and weekday
What is the output of this Python code?
Python
from datetime import datetime

date_str = '2024-06-20'
date_obj = datetime.strptime(date_str, '%Y-%m-%d')
print(date_obj.strftime('%A'))
AWednesday
BFriday
CThursday
DSaturday
Attempts:
2 left
💡 Hint
Check the weekday for June 20, 2024.
Predict Output
advanced
2:00remaining
Output of timezone-aware datetime conversion
What is the output of this Python code snippet?
Python
from datetime import datetime, timezone, timedelta

utc_time = datetime(2024, 6, 15, 12, 0, 0, tzinfo=timezone.utc)
new_york_tz = timezone(timedelta(hours=-4))
ny_time = utc_time.astimezone(new_york_tz)
print(ny_time.strftime('%Y-%m-%d %H:%M:%S %Z%z'))
A2024-06-15 08:00:00 UTC+0400
B2024-06-15 12:00:00 UTC-0400
C2024-06-15 16:00:00 UTC-0400
D2024-06-15 08:00:00 UTC-0400
Attempts:
2 left
💡 Hint
New York is 4 hours behind UTC in this example.
Predict Output
advanced
2:00remaining
Output of datetime replace method
What is the output of this Python code?
Python
from datetime import datetime

now = datetime(2024, 6, 15, 14, 30, 45)
new_time = now.replace(hour=9, minute=0, second=0)
print(new_time.strftime('%Y-%m-%d %H:%M:%S'))
A2024-06-15 09:30:45
B2024-06-15 09:00:00
C2024-06-15 14:30:45
D2024-06-15 00:00:00
Attempts:
2 left
💡 Hint
The replace method changes only specified parts of the datetime.
🧠 Conceptual
expert
2:00remaining
Error raised by invalid datetime string format
What error does this Python code raise?
Python
from datetime import datetime

invalid_date = '2024/06/15'
dt = datetime.strptime(invalid_date, '%Y-%m-%d')
AValueError
BTypeError
CSyntaxError
DKeyError
Attempts:
2 left
💡 Hint
The string format does not match the expected format.

Practice

(1/5)
1. Which Python module is commonly used to work with dates and times?
easy
A. os
B. math
C. random
D. datetime

Solution

  1. Step 1: Recall Python modules for date/time

    The datetime module provides classes for manipulating dates and times.
  2. Step 2: Identify unrelated modules

    math is for math functions, random for random numbers, os for operating system tasks.
  3. Final Answer:

    datetime -> Option D
  4. Quick Check:

    Module for date/time = datetime [OK]
Hint: Remember: datetime handles clocks and calendars [OK]
Common Mistakes:
  • Confusing datetime with math or random modules
  • Using os module for date/time
  • Not importing datetime before use
2. Which of the following is the correct way to create a date object for January 1, 2024 using the datetime module?
easy
A. date = datetime(2024, 1, 1)
B. date = datetime.date('2024-01-01')
C. date = datetime.date(2024, 1, 1)
D. date = datetime.date(1, 1, 2024)

Solution

  1. Step 1: Understand datetime.date constructor

    The date class constructor takes year, month, day as integers in that order.
  2. Step 2: Check each option

    date = datetime.date(2024, 1, 1) uses correct syntax: datetime.date(2024, 1, 1). date = datetime(2024, 1, 1) misses .date. date = datetime.date('2024-01-01') passes a string, which is invalid. date = datetime.date(1, 1, 2024) has wrong argument order.
  3. Final Answer:

    date = datetime.date(2024, 1, 1) -> Option C
  4. Quick Check:

    date(year, month, day) = correct order [OK]
Hint: Use datetime.date(year, month, day) with integers [OK]
Common Mistakes:
  • Passing date as string instead of integers
  • Wrong argument order
  • Missing .date after datetime
3. What will be the output of this code?
from datetime import date, timedelta
start = date(2024, 4, 25)
new_date = start + timedelta(days=10)
print(new_date)
medium
A. 2024-05-05
B. 2024-04-15
C. 2024-04-25
D. Error: unsupported operand

Solution

  1. Step 1: Understand timedelta addition

    Adding timedelta(days=10) to April 25, 2024 adds 10 days.
  2. Step 2: Calculate new date

    April 25 + 10 days = May 5, 2024.
  3. Final Answer:

    2024-05-05 -> Option A
  4. Quick Check:

    25 April + 10 days = 5 May [OK]
Hint: Add timedelta days to date to get new date [OK]
Common Mistakes:
  • Subtracting days instead of adding
  • Confusing timedelta with datetime
  • Expecting string input for timedelta
4. Find the error in this code snippet:
from datetime import datetime
dt = datetime(2024, 2, 30)
print(dt)
medium
A. datetime() requires string arguments
B. February 30 is an invalid date
C. Missing import for timedelta
D. print() cannot display datetime objects

Solution

  1. Step 1: Check date validity

    February 30 does not exist; February has max 29 days in leap years.
  2. Step 2: Understand datetime constructor

    datetime() expects valid year, month, day integers; invalid dates cause ValueError.
  3. Final Answer:

    February 30 is an invalid date -> Option B
  4. Quick Check:

    Invalid date causes error [OK]
Hint: Check if date exists before creating datetime [OK]
Common Mistakes:
  • Assuming all day numbers are valid
  • Missing import errors
  • Thinking print can't show datetime
5. You want to find how many days are between March 1, 2024 and April 15, 2024. Which code correctly calculates this?
hard
A. from datetime import date start = date(2024, 3, 1) end = date(2024, 4, 15) days = (end - start).days print(days)
B. from datetime import datetime start = datetime(2024, 3, 1) end = datetime(2024, 4, 15) days = end + start print(days)
C. from datetime import date days = date(2024, 4, 15) - 45 print(days)
D. from datetime import timedelta start = timedelta(days=2024) end = timedelta(days=101) days = end - start print(days)

Solution

  1. Step 1: Use date objects for subtraction

    Subtracting two date objects gives a timedelta representing the difference.
  2. Step 2: Extract days from timedelta

    Access the .days attribute to get the number of days between dates.
  3. Final Answer:

    45 -> Option A
  4. Quick Check:

    April 15 - March 1 = 45 days [OK]
Hint: Subtract dates, then use .days to get difference [OK]
Common Mistakes:
  • Adding dates instead of subtracting
  • Subtracting integer from date
  • Using timedelta incorrectly as date