Python · Syntax · Intermediate
datetime and json modules
Working with dates and times using the datetime module, and serializing data with the json module.
Quick topic start and explanations before exercises (exercises below):
timedelta arithmetic, calendar module, and isoweekday
#json.dumps/loads vs dump/load (files), serializing datetimes, object_hook
#Exercises:
Parse the string '2024-03-15' into a `datetime.date` object and return it.
from datetime import date
def parse_date(s):
# your code here
pass
print(parse_date('2024-03-15')) # 2024-03-15
print(type(parse_date('2024-03-15'))) # <class 'datetime.date'>
Solution
from datetime import date
def parse_date(s):
return date.fromisoformat(s)
Parse the string '15/03/2024 14:30' into a `datetime` object using `strptime`.
from datetime import datetime
def parse_datetime(s):
# your code here
pass
dt = parse_datetime('15/03/2024 14:30')
print(dt.year, dt.month, dt.day) # 2024 3 15
print(dt.hour, dt.minute) # 14 30
Solution
from datetime import datetime
def parse_datetime(s):
return datetime.strptime(s, '%d/%m/%Y %H:%M')
Given a `datetime` object, format it as 'March 15, 2024' (e.g., full month name, day, year).
from datetime import datetime
def format_date(dt):
# your code here
pass
from datetime import datetime
print(format_date(datetime(2024, 3, 15))) # March 15, 2024
print(format_date(datetime(2024, 11, 7))) # November 7, 2024
Solution
from datetime import datetime
def format_date(dt):
return dt.strftime('%B %-d, %Y')
Given two `date` objects, return the number of days between them (always positive).
from datetime import date
def days_between(d1, d2):
# your code here
pass
from datetime import date
print(days_between(date(2024, 1, 1), date(2024, 3, 15))) # 74
print(days_between(date(2024, 3, 15), date(2024, 1, 1))) # 74
Solution
from datetime import date
def days_between(d1, d2):
return abs((d2 - d1).days)
Serialize a dictionary to a JSON string. The dict may contain date objects — convert them to ISO strings (YYYY-MM-DD) before serializing.
import json
from datetime import date
def serialize(data):
# your code here
pass
d = {'name': 'Alice', 'birthday': date(1990, 5, 21), 'score': 42}
print(serialize(d)) # '{"name": "Alice", "birthday": "1990-05-21", "score": 42}'
Solution
import json
from datetime import date
def serialize(data):
def default(obj):
if isinstance(obj, date):
return obj.isoformat()
raise TypeError(f'Object of type {type(obj)} is not JSON serializable')
return json.dumps(data, default=default)
Parse a JSON string into a Python object. If a key ends with '_date', convert its value from a string to a `datetime.date`.
import json
from datetime import date
def deserialize(s):
# your code here
pass
s = '{"name": "Alice", "start_date": "2024-01-15", "score": 42}'
result = deserialize(s)
print(result['start_date']) # 2024-01-15
print(type(result['start_date'])) # <class 'datetime.date'>
print(result['score']) # 42
Solution
import json
from datetime import date
def deserialize(s):
def object_hook(d):
for k, v in d.items():
if k.endswith('_date') and isinstance(v, str):
d[k] = date.fromisoformat(v)
return d
return json.loads(s, object_hook=object_hook)
Given a list of ISO date strings, return them sorted from oldest to newest.
def sort_dates(dates):
# your code here
pass
dates = ['2024-11-01', '2023-03-15', '2024-01-20', '2022-12-31']
print(sort_dates(dates))
# ['2022-12-31', '2023-03-15', '2024-01-20', '2024-11-01']
Solution
def sort_dates(dates):
return sorted(dates)
Given a list of event dicts with an 'date' key (ISO string), return the event with the most recent date.
def latest_event(events):
# your code here
pass
events = [
{'name': 'Conference', 'date': '2024-09-12'},
{'name': 'Workshop', 'date': '2024-11-03'},
{'name': 'Meetup', 'date': '2024-07-20'},
]
print(latest_event(events)['name']) # Workshop
Solution
def latest_event(events):
return max(events, key=lambda e: e['date'])
Given a date, return the date of the first day of that month.
from datetime import date
def first_of_month(d):
# your code here
pass
from datetime import date
print(first_of_month(date(2024, 3, 15))) # 2024-03-01
print(first_of_month(date(2024, 12, 31))) # 2024-12-01
Solution
from datetime import date
def first_of_month(d):
return d.replace(day=1)
Given a list of JSON records (each with an 'amount' field), compute the total. Return 0 if the list is empty.
import json
def total_amount(records_json):
# your code here
pass
records = '[{"item": "book", "amount": 12.5}, {"item": "pen", "amount": 3.0}, {"item": "bag", "amount": 25.0}]'
print(total_amount(records)) # 40.5
print(total_amount('[]')) # 0
Solution
import json
def total_amount(records_json):
records = json.loads(records_json)
return sum(r['amount'] for r in records)