0
0
Pythonprogramming~20 mins

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

Choose your learning style9 modes available
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.