Find the bug · #53 · Strings and dates Hard Python
Late-night orders land on yesterday
Orders placed after midnight show up in the previous day’s sales report.
On this page
The report
An Indian shop’s daily sales report puts each order on the day it was placed. Orders placed between midnight and 5:30 am show up on the previous day, so Monday’s report includes some of Tuesday’s early orders.
The code
Read it first: what should it do? Then click the line where you think the bug is.
from datetime import datetime, timezone
def order_day(placed_at):
"""The calendar day an order belongs to in the daily report (the shop is in India)."""
return placed_at.astimezone(timezone.utc).date()Read it, then pick a line.
In which time zone does “the 29th” begin for an Indian shop? And which one does the code use?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
from datetime import timedelta
ist = timezone(timedelta(hours=5, minutes=30))
late = datetime(2026, 11, 29, 2, 0, tzinfo=ist)
print(order_day(late))It prints
2026-11-28
It should print
2026-11-29
Show the answer: the bug, the fix, and how you’d find it
The bug (line 5)
Line 5 converts the order time to UTC before taking its date. India is 5½ hours ahead of UTC, so 2:00 am on the 29th in India is 8:30 pm on the 28th in UTC, and the order lands on the 28th. A day in a report must be a day in the business’s own time zone: convert to IST, then take the date.
The fix
1from datetime import datetime, timezone1from datetime import datetime, timedelta, timezone2 3IST = timezone(timedelta(hours=5, minutes=30))4 3def order_day(placed_at):4 """The calendar day an order belongs to in the daily report (the shop is in India)."""5 return placed_at.astimezone(timezone.utc).date()7 return placed_at.astimezone(IST).date()How you’d find it
- Reproduce with an order at 2:00 am IST on the 29th: it comes out as the 28th. An order at 11 pm is fine.
- Only orders between midnight and 5:30 am move, and 5:30 is exactly India’s offset from UTC. So the day is being taken in UTC.
- The code converts to UTC on line 5. Storing times in UTC is right; taking the calendar day in UTC isn’t.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
from datetime import timedelta
ist = timezone(timedelta(hours=5, minutes=30))
assert order_day(datetime(2026, 11, 29, 2, 0, tzinfo=ist)).isoformat() == "2026-11-29"
assert order_day(datetime(2026, 11, 29, 23, 0, tzinfo=ist)).isoformat() == "2026-11-29"
assert order_day(datetime(2026, 11, 29, 0, 0, tzinfo=timezone.utc)).isoformat() == "2026-11-29"Where else this bites
- JavaScript’s
toISOString().slice(0, 10)gives the UTC date, often a day off in India. - Database queries with
DATE(created_at)on UTC timestamps.