Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

Data Analysis with Python (pandas, polars, DuckDB)  Module 8 – Dates and time series

Dates, times and time zones (IST and UTC)

Parse timestamps in pandas 3, store them in UTC, convert them to IST before grouping by date, measure durations and avoid naive and aware mix-ups.

  • Intermediate
  • 25 minutes
  • Examples run with Python 3.14.8, pandas 3.0.6, polars 1.44.2, duckdb 1.5.6 and Pyodide 314.0.7
  • By MySmartCoPilot
Free lesson, Pro answers: 25 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

What you will learn

  • Create, parse and format timestamps and use the .dt accessor
  • Store event instants in UTC and convert them to Asia/Kolkata for reporting
  • Compute durations with Timedelta and compare weekday conventions across tools
  • Avoid errors from comparing naive and time-zone-aware timestamps

Before you start

What you’ll learn · Before you start

What you will learn

  • Create, parse and format timestamps and use the .dt accessor
  • Store event instants in UTC and convert them to Asia/Kolkata for reporting
  • Compute durations with Timedelta and compare weekday conventions across tools
  • Avoid errors from comparing naive and time-zone-aware timestamps

Before you start

On this page

Fourteen logins form two UTC dates but three IST dates. Here, timestamps are modern event instants.

A timestamp names a moment, and a time zone says how a clock in one place reads that moment. Store every timestamp in UTC, keep the zone attached to the data, and convert to India Standard Time (IST, written Asia/Kolkata in code) only when you show, filter or group for readers in India. IST is UTC plus 5 hours 30 minutes all year, so every moment after 18:30 UTC already falls on the next IST date. A daily count that groups by the UTC date therefore puts late-evening activity on the wrong day. pandas calls a timestamp with a zone aware timestamp: A timestamp whose time zone and UTC offset identify its clock reading as a specific instant. and one without a zone naive timestamp: A clock reading with no time zone attached. It does not by itself identify which UTC instant the clock meant., and most time bugs come from mixing the two, or from treating a naive clock reading as if it named a moment.

A zone turns a clock reading into a moment

This lesson parses timestamps the ways logs write them, converts them, counts daily users on both clocks, measures durations, and shows which comparison mistake pandas stops and which one it lets through.

pd.to_datetime reads text into the datetime64 type, and what it returns depends on whether the text names a zone. Compare UTC text, offset text, a naive reading and epoch seconds. The naive reading still needs its source clock declared before it identifies an instant.

Clock meaning, precision and named zones Python · parse_and_zone.py
"""Parse aware instants, naive source clocks and epoch seconds without confusing their meanings."""
import pandas as pd

with_z = pd.to_datetime(pd.Series(["2026-10-04T18:45:00Z"]))
with_offset = pd.to_datetime(pd.Series(["2026-10-05T00:15:00+05:30"]))
no_zone = pd.to_datetime(pd.Series(["2026-10-04 18:45:00"]))
epoch = pd.to_datetime(pd.Series([1791139500]), unit="s")
print("Z suffix:      ", with_z.dtype)
print("+05:30 offset: ", with_offset.dtype)
print("no zone:       ", no_zone.dtype)
print("epoch seconds: ", epoch.dtype, "->", epoch.iloc[0])
print("epoch, utc=True:", pd.to_datetime(pd.Series([1791139500]), unit="s", utc=True).dtype)

mixed = pd.Series(["2026-10-04T18:45:00Z", "2026-10-05T00:15:00+05:30"])
try:
    pd.to_datetime(mixed)
except ValueError as error:
    print("\nTwo zones in one column:", str(error).split(".")[0])

utc = pd.to_datetime(mixed, utc=True)
print("\nWith utc=True, both rows are the same moment:")
print(utc.to_string())
ist = utc.dt.tz_convert("Asia/Kolkata")
print("\nConverted to IST:")
print(ist.to_string())
print("Zone object:", repr(ist.dt.tz))

precise = pd.to_datetime(pd.Series(["2026-10-04T18:45:00.123456789Z"]), utc=True)
print("\nNine fractional digits:", precise.dtype, "->", precise.iloc[0])
historical = pd.Timestamp("1944-01-01T03:00:00Z")
print("Historical named zone:", historical.tz_convert("Asia/Kolkata"))
print("Historical fixed +05:30:", historical.tz_convert("UTC+05:30"))

till_clock = pd.to_datetime(pd.Series(["2026-10-05 00:15:00"]))
declared_ist = till_clock.dt.tz_localize("Asia/Kolkata").dt.tz_convert("UTC")
assumed_utc = pd.to_datetime(till_clock, utc=True)
print("\nThe till wrote naive IST clock readings:")
print("Declared IST, converted to UTC:", declared_ist.iloc[0])
print("utc=True assumes a UTC source: ", assumed_utc.iloc[0])
print("Wrong-source difference in minutes:",
      (assumed_utc.iloc[0] - declared_ist.iloc[0]) / pd.Timedelta(minutes=1))

Output

Z suffix:       datetime64[us, UTC]
+05:30 offset:  datetime64[us, UTC+05:30]
no zone:        datetime64[us]
epoch seconds:  datetime64[s] -> 2026-10-04 18:45:00
epoch, utc=True: datetime64[s, UTC]

Two zones in one column: Mixed timezones detected

With utc=True, both rows are the same moment:
0   2026-10-04 18:45:00+00:00
1   2026-10-04 18:45:00+00:00

Converted to IST:
0   2026-10-05 00:15:00+05:30
1   2026-10-05 00:15:00+05:30
Zone object: zoneinfo.ZoneInfo(key='Asia/Kolkata')

Nine fractional digits: datetime64[ns, UTC] -> 2026-10-04 18:45:00.123456789+00:00
Historical named zone: 1944-01-01 09:30:00+06:30
Historical fixed +05:30: 1944-01-01 08:30:00+05:30

The till wrote naive IST clock readings:
Declared IST, converted to UTC: 2026-10-04 18:45:00+00:00
utc=True assumes a UTC source:  2026-10-05 00:15:00+00:00
Wrong-source difference in minutes: 330.0

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 parse_and_zone.py

In a local copy, shorten the nine fractional digits to six and inspect the resulting dtype. Keep the instant and the resolution separate when you interpret the output.

A Z at the end means UTC, so the first value is aware, with the type datetime64[us, UTC]. pandas 3 parses this whole-second text to microseconds (us), where pandas 2 used nanoseconds. Text with nine fractional digits instead keeps nanosecond resolution, as the extra precision row of the same program shows; do not assume every parsed column has the same unit. The second value carries an offset of +05:30, and pandas keeps exactly that: a fixed offset, UTC+05:30, which is not the named zone Asia/Kolkata. The third has no zone at all, so it is naive: pandas knows the clock reading and nothing about where the clock was. Epoch seconds count from the Unix epoch, a moment defined in UTC, but unit="s" still returns a naive value unless you also pass utc=True.

Text with two different zones in one column stops pandas 3 with a ValueError instead of producing a column of mixed objects. utc=True turns every row into a UTC moment, and the output shows that the two strings named the same instant. dt.tz_convert("Asia/Kolkata") then changes the clock reading and nothing else. The zone object is a zoneinfo.ZoneInfo, because pandas 3 uses the standard library’s zoneinfo module by default for a named-zone string, as its release notes say. The historical rows also show why a zone name is more than a fixed offset: the database’s rules give that older Kolkata instant an offset of +06:30, while a fixed +05:30 stays unchanged.

The till-clock example isolates a different mistake. Localizing its known IST reading and then converting gives 18:45 UTC; utc=True instead declares that the naive reading was UTC and places it 330 minutes late.

Follow the source forms into one UTC instant, then inspect which values still lack a declared clock.

Interactive · stage by stage One instant, different representations Step through the strings from parse_and_zone.py and keep the instant separate from its clock and precision.
One instant, different representations, step 4 of 4. Showing Parse the four forms, Unify aware input, Show the IST clock. In focus: Parse the four forms.Parse the four formsZ, offset, naive, epochUnify aware inpututc=TrueShow the IST clock00:15 next date

The drawing shows the whole scene; its 4 steps are listed below.

Every step as text
  1. Read what the source means. 18:45 with Z and 00:15 with +05:30 describe the same instant. The string without a zone is only a clock reading; epoch seconds have a UTC meaning but the default parsed result is naive.
  2. Do not mix offsets silently. Parsing the two aware strings together without a policy raises ValueError. utc=True makes both rows 18:45 UTC; it must not be used to pretend a naive IST clock was UTC.
  3. Convert the clock, keep time. Converting the UTC rows to Asia/Kolkata gives 00:15 on the next date. The named zone can carry historical rules that a fixed +05:30 offset does not carry.
  4. Keep the actual precision. The whole-second text is stored in microseconds here, while the nine-digit fractional input is stored in nanoseconds. Check the dtype rather than assuming one timestamp resolution.

Key idea

Interpret the source clock before conversion, and retain the precision the parsed values actually require.

Checkpoint

Check: Zones and timestamp precision

  1. Question 1 of 2 What is still unknown in a timestamp parsed from a clock reading with no zone?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Which local clock supplied the reading

    A dtype represents the value; awareness describes whether the clock reading identifies an instant.

  2. Question 2 of 2 A parser returns datetime64[ns, UTC] for text with nine fractional digits. Should you force every value to microseconds?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Only under an explicit precision and rounding contract

    The whole-second example uses microseconds; the more precise input uses nanoseconds. Check and retain the actual representation.

Convert before taking the date or hour

The rule that matters most in practice is the order of two steps: convert first, then take the date or the hour. The examples use 14 logins from a weekend, stored in UTC:

logins.csv: 14 logins, stored in UTC CSV · logins.csv
user_id,login_utc
u01,2026-10-03T03:10:00Z
u02,2026-10-03T06:55:00Z
u03,2026-10-03T15:40:00Z
u04,2026-10-03T16:05:00Z
u01,2026-10-03T19:20:00Z
u05,2026-10-03T20:45:00Z
u02,2026-10-04T02:30:00Z
u06,2026-10-04T05:15:00Z
u03,2026-10-04T15:35:00Z
u07,2026-10-04T15:50:00Z
u04,2026-10-04T16:20:00Z
u08,2026-10-04T18:40:00Z
u05,2026-10-04T19:05:00Z
u09,2026-10-04T22:30:00Z
The same evening on UTC and IST clocks: 18:30 UTC is midnight IST, and the two late UTC logins belong to Sunday in IST.One evening, two clocksUTC span: 12:00 to 24:00IST span: 17:30 to 05:30Saturday to Sunday in IST18:30 UTC = 00:00 ISTThe IST date changes here.u03: 15:40 UTC21:10 ISTIST Saturdayu04: 16:05 UTC21:35 ISTIST Saturdayu01: 19:20 UTC00:50 ISTIST Sundayu05: 20:45 UTC02:15 ISTIST SundaySame instants; local dates differ.

One evening on two clocks

Text description of the diagram

The same time span runs from 12:00 to 24:00 Saturday in UTC and from 17:30 Saturday to 05:30 Sunday in modern IST. The dashed boundary marks 18:30 UTC, exactly 00:00 Sunday IST. The four event cards retain the original example's instants: u03 at 15:40 UTC is 21:10 IST Saturday; u04 at 16:05 UTC is 21:35 IST Saturday; u01 at 19:20 UTC is 00:50 IST Sunday; u05 at 20:45 UTC is 02:15 IST Sunday. The outlined Sunday cards also say Sunday in words, so color is not the only date cue.

Daily active users and the busiest hours on both clocks Python · logins_by_ist_date.py
"""Daily active users and the busiest hours, counted in UTC and in IST."""
import pandas as pd

logins = pd.read_csv("logins.csv")
logins["utc"] = pd.to_datetime(logins["login_utc"], utc=True)
logins["ist"] = logins["utc"].dt.tz_convert("Asia/Kolkata")

by_utc_date = logins.groupby(logins["utc"].dt.date)["user_id"].nunique()
by_ist_date = logins.groupby(logins["ist"].dt.date)["user_id"].nunique()
print("Daily active users by UTC date:")
print(by_utc_date.rename_axis("UTC date").to_string())
print("\nDaily active users by IST date:")
print(by_ist_date.rename_axis("IST date").to_string())

moved = logins[logins["utc"].dt.date != logins["ist"].dt.date]
print(f"\n{len(moved)} of {len(logins)} logins fall on the next date in IST:")
print(moved[["user_id", "utc", "ist"]].to_string(index=False))


def busiest(hours, label):
    """The three hours with the most logins (the earlier hour first on a tie)."""
    counts = hours.value_counts().sort_index().sort_values(ascending=False, kind="stable")
    return counts.head(3).rename_axis(label).rename("logins").to_string()


print("\nBusiest hours in IST:")
print(busiest(logins["ist"].dt.hour, "IST hour"))
print("\nBusiest hours in UTC:")
print(busiest(logins["utc"].dt.hour, "UTC hour"))

Output

Daily active users by UTC date:
UTC date
2026-10-03    5
2026-10-04    8

Daily active users by IST date:
IST date
2026-10-03    4
2026-10-04    7
2026-10-05    3

5 of 14 logins fall on the next date in IST:
user_id                       utc                       ist
    u01 2026-10-03 19:20:00+00:00 2026-10-04 00:50:00+05:30
    u05 2026-10-03 20:45:00+00:00 2026-10-04 02:15:00+05:30
    u08 2026-10-04 18:40:00+00:00 2026-10-05 00:10:00+05:30
    u05 2026-10-04 19:05:00+00:00 2026-10-05 00:35:00+05:30
    u09 2026-10-04 22:30:00+00:00 2026-10-05 04:00:00+05:30

Busiest hours in IST:
IST hour
21    5
0     3
8     2

Busiest hours in UTC:
UTC hour
15    3
16    2
19    2

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 logins_by_ist_date.py

Grouped by the UTC date, the weekend has two days with 5 and 8 users. Grouped by the IST date, the same 14 logins spread over three days with 4, 7 and 3 users, because 5 logins happened after 18:30 UTC. Neither table is wrong as arithmetic, but only the second answers “how many people used the app on Sunday” for a team in India.

Hours show a second effect. The busiest IST hour is 21:00, with 5 logins. In UTC those 5 logins are split between 15:00 and 16:00, because the IST hour from 21:00 to 22:00 runs from 15:30 to 16:30 UTC. An offset with half an hour in it means that an hourly UTC table can never be relabelled into IST hours afterwards: the conversion has to happen row by row, before the grouping.

Watch the five date-boundary crossings, then compare the distinct-user counts and the half-hour-shifted hour buckets.

Interactive · stage by stage The same 14 logins on two clocks Follow conversion before extracting the date; compare the daily users with the unchanged login fixture.
The same 14 logins on two clocks, step 4 of 4. Showing 14 UTC login events, Convert each instant, Extract the local date, Count the local hour. In focus: Count the local hour.14 UTC login events5 logins cross midnightConvert each instantUTC to Asia/KolkataExtract the local date4, 7 and 3 distinct usersCount the local hourIST hour 21 has 5 logins

The drawing shows the whole scene; its 4 steps are listed below.

Every step as text
  1. Start from the source rows. The fixture has 14 login events. Grouping their UTC dates gives 5 and 8 distinct users; this is a UTC-day metric.
  2. Cross the date boundary. Two Saturday UTC logins by u01 and u05 become Sunday IST logins. Three Sunday UTC logins become Monday IST logins, so five events move to the next IST date.
  3. Group after conversion. Taking the IST date now gives daily distinct-user counts of 4, 7 and 3. Their sum is not a count of distinct users for the whole weekend; a user may appear on more than one date.
  4. Keep the half hour. The five logins in IST hour 21 are split across UTC hours 15 and 16. Relabelling aggregated UTC hours cannot reconstruct these IST-hour buckets.

Key idea

Convert each instant before extracting the local date or hour; an already aggregated UTC bucket has lost information.

Checkpoint

Check: Conversion before grouping

  1. Question 1 of 2 How many minutes ahead of UTC is modern IST?

    Type a number.

    Show the answer: Question 1 of 2

    Answer: 330 minutes

    Five hours plus thirty minutes is 5 × 60 + 30 = 330 minutes.

  2. Question 2 of 2 The fixture's IST hour 21 has five logins. How many UTC-hour buckets contain those same five logins?

    Type a number.

    Show the answer: Question 2 of 2

    Answer: 2 buckets

    IST 21:00–22:00 maps to UTC 15:30–16:30, crossing UTC hours 15 and 16.

Keep datetime values until the report is ready

Once a column has the datetime64 type, the .dt accessor reads its parts in the column’s own zone: dt.hour, dt.day_name(), dt.date and many more. Two of them look alike and behave differently.

Fields for computing, text for reading Python · dt_fields.py
"""The .dt accessor: fields to compute with, and text for people to read."""
import pandas as pd

ist = pd.to_datetime(
    pd.Series(["2026-09-28T04:30:00Z", "2026-10-04T15:35:00Z", "2026-10-04T18:40:00Z"]), utc=True
).dt.tz_convert("Asia/Kolkata")

fields = pd.DataFrame({
    "ist": ist,
    "date": ist.dt.date,
    "day_start": ist.dt.floor("D"),
    "hour": ist.dt.hour,
    "weekday": ist.dt.day_name(),
})
print(fields.to_string(index=False))
print("\ndate:", fields["date"].dtype, "| day_start:", fields["day_start"].dtype)

shown = ist.dt.strftime("%d %b %Y, %I:%M %p")
print("\nFor a report:", shown.tolist(), shown.dtype)
print("Sorted as text:   ", sorted(shown))
print("Sorted as moments:", shown[ist.sort_values().index].tolist())

Output

                      ist       date                 day_start  hour weekday
2026-09-28 10:00:00+05:30 2026-09-28 2026-09-28 00:00:00+05:30    10  Monday
2026-10-04 21:05:00+05:30 2026-10-04 2026-10-04 00:00:00+05:30    21  Sunday
2026-10-05 00:10:00+05:30 2026-10-05 2026-10-05 00:00:00+05:30     0  Monday

date: object | day_start: datetime64[us, Asia/Kolkata]

For a report: ['28 Sep 2026, 10:00 AM', '04 Oct 2026, 09:05 PM', '05 Oct 2026, 12:10 AM'] str
Sorted as text:    ['04 Oct 2026, 09:05 PM', '05 Oct 2026, 12:10 AM', '28 Sep 2026, 10:00 AM']
Sorted as moments: ['28 Sep 2026, 10:00 AM', '04 Oct 2026, 09:05 PM', '05 Oct 2026, 12:10 AM']

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 dt_fields.py

dt.date returns plain Python date objects, stored with the object type, which is fine as a grouping key but loses the zone and the fast datetime methods. dt.floor("D") keeps the datetime64 type and the zone, so the start of each IST day can still be compared, sorted and converted. dt.strftime turns timestamps into text with the str type, which suits a report and nothing else: sorted as text, the September login lands after the two October ones, because “28” sorts after “04”. Format at the very end, after all filtering, sorting and grouping.

Follow the three timestamps through field extraction and formatting; check where lexical sorting puts September.

Interactive · stage by stage Compute with values, display with text Follow the three timestamps from dt_fields.py and compare the order before and after formatting.
Compute with values, display with text, step 3 of 3. Showing Aware datetime values, Extract report fields, Format at the end. In focus: Format at the end.Aware datetime values10:00, 21:05, 00:10 ISTExtract report fieldsdate, floor, hour, weekdayFormat at the endSeptember precedes October

The drawing shows the whole scene; its 3 steps are listed below.

Every step as text
  1. Keep the typed instants. The three IST timestamps retain their time zone and can be sorted as moments. The September timestamp is earlier than both October timestamps.
  2. Choose the field's type. dt.date gives Python date objects without a zone. dt.floor('D') keeps aware datetime values at local midnight; dt.hour and dt.day_name use the column's own clock.
  3. Do not sort display labels. The display strings start with 28, 04 and 05. Lexical sorting puts 04 and 05 before 28, so it moves September after October; format only after the datetime sorting is finished.

Key idea

Use datetime fields for computation and sort instants before creating display strings.

Checkpoint

Check: Datetime fields and display text

  1. Question 1 of 2 Which representation keeps a time zone while identifying local midnight?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: dt.floor("D") on the aware column

    Date objects, aware midnight values and display strings serve different jobs even when they print similar dates.

  2. Question 2 of 2 An earlier month's display label starts with a larger day number than a later month's label. What keeps chronological order?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Sort the datetime values, then format them

    A report label is not a sortable time key. Retain the datetime until filtering and sorting are complete.

Subtract instants to measure elapsed duration

Subtracting two timestamps gives a Timedelta, an exact length of time. Both columns must be aware, or both naive; here both are UTC. The final calculation crosses UTC midnight from 23:50 to 00:20 on the next date and returns 30 minutes. Naive local clock readings across a clock change do not establish elapsed time: identify their instants before measuring a duration.

Session lengths, in minutes and as a data check Python · session_lengths.py
"""Session lengths as Timedelta values: in minutes, in parts, and as a check on the data."""
import pandas as pd

sessions = pd.DataFrame({
    "user_id": ["u03", "u07", "u08", "u09"],
    "start": ["2026-10-04T15:35:00Z", "2026-10-04T15:50:00Z", "2026-10-04T18:40:00Z", "2026-10-04T22:30:00Z"],
    "end": ["2026-10-04T16:17:30Z", "2026-10-04T15:50:45Z", "2026-10-04T19:25:00Z", "2026-10-04T22:28:00Z"],
})
for column in ["start", "end"]:
    sessions[column] = pd.to_datetime(sessions[column], utc=True)

sessions["length"] = sessions["end"] - sessions["start"]
sessions["minutes"] = sessions["length"] / pd.Timedelta(minutes=1)
print(sessions[["user_id", "length", "minutes"]].to_string(index=False))
print("\ndtype:", sessions["length"].dtype)
print("parts of the first length:", sessions["length"].dt.components.iloc[0][["hours", "minutes", "seconds"]].tolist())

bad = sessions[sessions["length"] < pd.Timedelta(0)]
print("\nSessions that end before they start:", bad["user_id"].tolist())
good = sessions.drop(bad.index)
print("Median of the others:", good["length"].median())
print("A 30-minute timeout after the first start:", (sessions["start"].iloc[0] + pd.Timedelta(minutes=30)).tz_convert("Asia/Kolkata"))

across_midnight = pd.Timestamp("2026-10-05T00:20:00Z") - pd.Timestamp("2026-10-04T23:50:00Z")
print("A UTC session from 23:50 to 00:20 next date:", across_midnight / pd.Timedelta(minutes=1), "minutes")

Output

user_id            length  minutes
    u03   0 days 00:42:30    42.50
    u07   0 days 00:00:45     0.75
    u08   0 days 00:45:00    45.00
    u09 -1 days +23:58:00    -2.00

dtype: timedelta64[us]
parts of the first length: [0, 42, 30]

Sessions that end before they start: ['u09']
Median of the others: 0 days 00:42:30
A 30-minute timeout after the first start: 2026-10-04 21:35:00+05:30
A UTC session from 23:50 to 00:20 next date: 30.0 minutes

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 session_lengths.py

Dividing by pd.Timedelta(minutes=1) turns a length into a plain number of minutes, which charts and averages need, and dt.components splits it into days, hours, minutes and seconds. The last session ends two minutes before it starts, and pandas shows that as -1 days +23:58:00: minus one day plus 23 hours 58 minutes, which is minus 2 minutes. A negative length is a data problem, such as two devices with unsynchronised clocks, so filter it out and count it before you report a median or an average. Adding a Timedelta to a timestamp works the other way, for example to find when a 30-minute session timeout expires.

Inspect the four session lengths, flag the negative interval, then check the denominator of the valid-session summary.

Interactive · stage by stage Inspect lengths before summarizing Follow the four sessions from session_lengths.py and keep an invalid interval out of the summary.
Inspect lengths before summarizing, step 3 of 3. Showing Subtract aware instants, Flag negative lengths, Summarize valid sessions. In focus: Summarize valid sessions.Subtract aware instants42.5, 0.75, 45, -2 minFlag negative lengthsu09 ends before its startSummarize valid sessionsMedian 42.5 minutes

The drawing shows the whole scene; its 3 steps are listed below.

Every step as text
  1. Measure the same timeline. Both columns are aware UTC values. Subtraction gives session lengths of 42.5, 0.75, 45 and -2 minutes, independent of their displayed local clocks.
  2. Read the negative interval. The -1 days +23:58:00 representation is minus two minutes. u09's end precedes its start, so flag and count this invalid session before computing a summary.
  3. Keep the denominator explicit. The remaining three lengths have median 42.5 minutes. A 30-minute timeout adds an elapsed duration to the first start; it is a different calculation from advancing a civil date.

Key idea

Measure elapsed durations on identified instants, and count invalid sessions before summarizing the valid ones.

Checkpoint

Check: Elapsed durations

  1. Question 1 of 2 What does -1 days +23:58:00 represent?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Minus two minutes

    Timedelta's normalized display can split a negative interval into a negative day and a positive remainder.

  2. Question 2 of 2 A valid session starts at 10:00 UTC and ends at 10:42:30 UTC. What is its length in minutes?

    Type a number.

    Show the answer: Question 2 of 2

    Answer: 42.5 minutes

    Forty-two minutes and thirty seconds is 42 + 30/60 = 42.5 minutes.

A calendar day can differ from 24 hours

Many zones move their clocks twice a year, and pandas 3 changed what “one day later” means across such a change. The UK, for example, puts its clocks forward at 01:00 on the last Sunday of March, according to GOV.UK, and the example starts the day before that change:

A calendar day against 24 hours, in London and in Kolkata Python · day_vs_24_hours.py
"""A calendar day against 24 hours, in London (clocks change) and in Kolkata (they never do)."""
import pandas as pd

for zone in ["Europe/London", "Asia/Kolkata"]:
    start = pd.Timestamp("2026-03-28 08:00", tz=zone)
    print(zone)
    print("  start:           ", start)
    print("  + Day(1):        ", start + pd.offsets.Day(1))
    print("  + 24 hours:      ", start + pd.Timedelta(hours=24))
    day = pd.Timestamp("2026-03-30", tz=zone) - pd.Timestamp("2026-03-29", tz=zone)
    print("  length of the day the UK clocks change:", day)

try:
    pd.Timestamp("2026-03-29 01:30").tz_localize("Europe/London")
except ValueError as error:
    print("\nLondon, 01:30 that night:", error)

Output

Europe/London
  start:            2026-03-28 08:00:00+00:00
  + Day(1):         2026-03-29 08:00:00+01:00
  + 24 hours:       2026-03-29 09:00:00+01:00
  length of the day the UK clocks change: 0 days 23:00:00
Asia/Kolkata
  start:            2026-03-28 08:00:00+05:30
  + Day(1):         2026-03-29 08:00:00+05:30
  + 24 hours:       2026-03-29 08:00:00+05:30
  length of the day the UK clocks change: 1 days 00:00:00

London, 01:30 that night: 2026-03-29 01:30:00 is a nonexistent time due to daylight savings time. Try using the 'nonexistent' argument.

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 day_vs_24_hours.py

In pandas 3, pd.offsets.Day(1) is a calendar day: 08:00 on Saturday plus one day is 08:00 on Sunday, even though only 23 hours passed in London. pd.Timedelta(hours=24) is always 24 hours and lands at 09:00 on the London clock. The pandas 3 release notes describe this change: Day used to mean a fixed 24 hours. A schedule such as “every day at 08:00” needs the calendar day; a measured duration such as “24 hours after the order” needs the Timedelta. A wall-clock time inside the skipped hour, such as 01:30 that night, never happened, and tz_localize raises a ValueError for it unless you choose what to do with the nonexistent argument.

In Asia/Kolkata both additions give the same answer and every day lasts 24 hours. The IANA Time Zone Database, which zoneinfo reads, has kept Asia/Kolkata at UTC+05:30 without any daylight saving rule since 1945, and it records the offsets and rules of every other zone too, so an Indian dataset that meets London or New York times is handled correctly as long as each value carries the right zone name.

Keep Saturday’s 08:00 in focus and compare the Sunday clock reached by a civil day with the one reached after 24 hours.

Interactive · stage by stage Two meanings of one day later Step through day_vs_24_hours.py at the London clock change, then compare the Kolkata control.
Two meanings of one day later, step 4 of 4. Showing Start at 08:00 Saturday, Advance one calendar day, Advance 24 elapsed hours, Compare Kolkata. In focus: Compare Kolkata.Start at 08:00 SaturdayLondon before the changeAdvance one calendar day08:00 Sunday; 23h elapsedAdvance 24 elapsed hours09:00 SundayCompare KolkataBoth give 08:00 Sunday

The drawing shows the whole scene; its 4 steps are listed below.

Every step as text
  1. Begin on the local clock. The London timestamp starts at 08:00 on the Saturday before the spring clock change. Its current offset is UTC+00:00.
  2. Keep the civil clock reading. pandas 3 Day(1) reaches 08:00 Sunday. London has moved to UTC+01:00, so only 23 elapsed hours separate the two instants.
  3. Keep elapsed time instead. Timedelta(hours=24) reaches 09:00 Sunday. It adds exactly 24 hours rather than promising the same local clock reading.
  4. Use the fixed-offset control. Kolkata does not change offset on these dates, so both operations reach 08:00 and the day lasts 24 hours. London 01:30 in the skipped hour needs an explicit nonexistent-time policy.

Key idea

A calendar-day step keeps a civil clock promise, while a Timedelta keeps an elapsed-time promise.

Checkpoint

Check: Calendar days and elapsed time

  1. Question 1 of 2 Which promise does pd.Timedelta(hours=24) make?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Exactly 24 elapsed hours

    An elapsed interval and a recurring local-clock schedule need different operations.

  2. Question 2 of 2 London is 08:00 on the Saturday before the spring clock change. What Sunday hour does adding 24 hours reach?

    Type a number.

    Show the answer: Question 2 of 2

    Answer: 9 hour

    The UTC offset advances by one hour; 24 elapsed hours lands at 09:00 on the new local clock.

Normalize weekday conventions before comparing

“Day 1 of the week” depends on the tool. One week, from a Monday to a Sunday, numbered by three engines:

One week, numbered three ways Python · weekday_numbers.py
"""One week, numbered by pandas, polars and DuckDB."""
import duckdb
import pandas as pd
import polars as pl

week = pd.DataFrame({"day": pd.date_range("2026-09-28", "2026-10-04", freq="D")})
iso = week["day"].dt.isocalendar()
con = duckdb.connect()
con.execute("SET enable_progress_bar = false")
sql = con.sql("SELECT dayofweek(day) AS dow, isodow(day) AS isodow FROM week ORDER BY day").df()

table = pd.DataFrame({
    "date": week["day"].dt.strftime("%Y-%m-%d"),
    "day": week["day"].dt.day_name().str[:3],
    "pandas dayofweek": week["day"].dt.dayofweek,
    "pandas ISO day": iso["day"].to_numpy(),
    "polars weekday": pl.Series(week["day"].dt.date.tolist()).dt.weekday().to_list(),
    "DuckDB dayofweek": sql["dow"],
    "DuckDB isodow": sql["isodow"],
})
print(table.to_string(index=False))
print("\nISO year, week and day of the Sunday:", iso.iloc[-1].tolist())

boundary = pd.Series(pd.to_datetime(["2021-01-01", "2021-01-04"]))
new_year = boundary.dt.isocalendar()
print("\nCalendar year and ISO year at New Year:")
print(pd.DataFrame({
    "date": boundary.dt.strftime("%Y-%m-%d"),
    "calendar year": boundary.dt.year,
    "ISO year": new_year["year"],
    "ISO week": new_year["week"],
    "ISO day": new_year["day"],
}).to_string(index=False))

Output

      date day  pandas dayofweek  pandas ISO day  polars weekday  DuckDB dayofweek  DuckDB isodow
2026-09-28 Mon                 0               1               1                 1              1
2026-09-29 Tue                 1               2               2                 2              2
2026-09-30 Wed                 2               3               3                 3              3
2026-10-01 Thu                 3               4               4                 4              4
2026-10-02 Fri                 4               5               5                 5              5
2026-10-03 Sat                 5               6               6                 6              6
2026-10-04 Sun                 6               7               7                 0              7

ISO year, week and day of the Sunday: [2026, 40, 7]

Calendar year and ISO year at New Year:
      date  calendar year  ISO year  ISO week  ISO day
2021-01-01           2021      2020        53        5
2021-01-04           2021      2021         1        1

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 weekday_numbers.py

Select the receiving convention in the table, and watch which raw numbers need a conversion:

Interactive · answer and compare Choose the receiving weekday convention Select the convention your report expects and compare the Monday and Sunday values from the recorded week.
Which raw numbering convention does the receiving report require?

Answer the question above: the table then marks what fits your case and says why the rest does not.

Weekday numbering from the same seven dates
Accessor Monday as zero Sunday as zero ISO weekday
pandas weekday Call: dt.dayofweek Good Monday 0; Sunday 6 Poor Sunday 6; Monday 0 Poor Monday 0; Sunday 6, so map before comparing
pandas ISO day Call: dt.isocalendar().day Poor Monday 1; Sunday 7 Poor Sunday 7; Monday 1 Good Monday 1 through Sunday 7
polars weekday Call: dt.weekday() Poor Monday 1; Sunday 7 Poor Sunday 7; Monday 1 Good Monday 1 through Sunday 7
DuckDB weekday Call: dayofweek Poor Monday 1; Sunday 0 Good Sunday 0; Monday 1 Poor Monday 1; Sunday 0, so map before comparing
DuckDB ISO day Call: isodow Poor Monday 1; Sunday 7 Poor Sunday 7; Monday 1 Good Monday 1 through Sunday 7
How the answers decide
  • “Which raw numbering convention does the receiving report require?” Monday 0 through Sunday 6: rules out pandas ISO day, polars weekday, DuckDB weekday and DuckDB ISO day. Only pandas dayofweek already has Monday 0 and Sunday 6. The other raw numbers need a declared conversion.
  • “Which raw numbering convention does the receiving report require?” Sunday 0 through Saturday 6: rules out pandas weekday, pandas ISO day, polars weekday and DuckDB ISO day. DuckDB dayofweek has Sunday 0; the other raw outputs do not follow this convention.
  • “Which raw numbering convention does the receiving report require?” Monday 1 through Sunday 7: rules out pandas weekday and DuckDB weekday. pandas isocalendar day, polars weekday and DuckDB isodow already use Monday 1 through Sunday 7.

pandas’ dt.dayofweek starts from Monday = 0, DuckDB’s dayofweek from Sunday = 0, and polars’ weekday and DuckDB’s isodow use the ISO 8601 numbering, Monday = 1 to Sunday = 7. A filter such as “weekday < 5 means a working day” is right in pandas and wrong in DuckDB, so compare day names in tests, or use the ISO number everywhere. The ISO calendar also numbers weeks: the Sunday of this week is day 7 of ISO week 40, and ISO weeks always start on a Monday. The final New Year table separates the two year fields: its first January date belongs to the previous ISO year, while the following Monday starts ISO week 1. Pair an ISO week number with its ISO year, rather than its calendar year.

Key idea

Translate the weekday convention before comparing raw numbers from different engines.

Checkpoint

Check: Weekday conventions

  1. Question 1 of 2 What range does an ISO weekday use?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Monday 1 through Sunday 7

    Choose the receiving convention before comparing ordinal weekday numbers.

  2. Question 2 of 2 A DuckDB dayofweek value is 0. An ISO-based report should show which day number?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: 7, Sunday

    DuckDB has Sunday 0; ISO has Monday 1 through Sunday 7. The conversion must treat the Sunday boundary correctly.

Give a naive cutoff its intended zone

pandas refuses some comparisons between aware and naive values and quietly answers others. Both behaviours are in this example, with the fix:

An error, a silent False, and the fix Python · naive_vs_aware.py
"""Comparing aware timestamps (with a zone) and naive ones (without): one error, one silent mistake."""
import pandas as pd

logins = pd.to_datetime(pd.Series(["2026-10-04T15:35:00Z", "2026-10-04T18:40:00Z"]), utc=True)
cutoff = pd.Timestamp("2026-10-05 00:00")  # meant as midnight in IST, written without a zone

try:
    logins < cutoff
except TypeError as error:
    print("logins < cutoff ->", type(error).__name__ + ":", error)

same_moment = pd.Timestamp("2026-10-04 15:35")  # the first login's UTC time, without a zone
print("logins == same_moment ->", (logins == same_moment).tolist())

cutoff_ist = cutoff.tz_localize("Asia/Kolkata")
print("\nWith the zone attached:", cutoff_ist)
print("logins < cutoff_ist ->", (logins < cutoff_ist).tolist())
print("logins == same_moment in UTC ->", (logins == same_moment.tz_localize("UTC")).tolist())

ist = logins.dt.tz_convert("Asia/Kolkata")
print("\nRemove zone, keep local clock:", ist.dt.tz_localize(None).tolist())
print("Convert to UTC, remove zone:", ist.dt.tz_convert(None).tolist())

Output

logins < cutoff -> TypeError: Invalid comparison between dtype=datetime64[us, UTC] and Timestamp
logins == same_moment -> [False, False]

With the zone attached: 2026-10-05 00:00:00+05:30
logins < cutoff_ist -> [True, False]
logins == same_moment in UTC -> [True, False]

Remove zone, keep local clock: [Timestamp('2026-10-04 21:05:00'), Timestamp('2026-10-05 00:10:00')]
Convert to UTC, remove zone: [Timestamp('2026-10-04 15:35:00'), Timestamp('2026-10-04 18:40:00')]

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 naive_vs_aware.py

In a local copy, move the intended IST cutoff to 01:00 and predict the two Boolean results before running it. Attach the intended zone before comparing.

Ordering an aware column against a naive cutoff raises a TypeError, which is the helpful case: the code stops. Testing equality does not raise. Every row compares as False, so a filter written with == silently returns nothing, even for a row whose clock reading matches. The fix is the same for both: say which zone the naive value belongs to with tz_localize, here Asia/Kolkata for a cutoff meant as midnight in India. The 18:40 UTC login is then correctly after midnight IST. A plain string such as "2026-10-05" is read in the column’s own zone, which is convenient when the column is already converted, and a trap when nobody remembers which zone it holds.

Localize the intended midnight cutoff and compare the two login instants; contrast the ordering error with silent equality.

Interactive · stage by stage Attach the cutoff's intended clock Follow the two UTC logins and the naive midnight cutoff from naive_vs_aware.py.
Attach the cutoff's intended clock, step 4 of 4. Showing Logins and naive cutoff, Declare midnight IST, Compare the instants. In focus: Compare the instants.Logins and naive cutoff15:35 and 18:40 UTCDeclare midnight IST00:00 IST is 18:30 UTCCompare the instantsBefore cutoff: True, False

The drawing shows the whole scene; its 4 steps are listed below.

Every step as text
  1. Let ordering fail loudly. The naive cutoff has no zone. Comparing the aware UTC column with it using less-than raises TypeError instead of choosing a clock for the caller.
  2. Notice the silent equality. Equality against a naive timestamp with the first login's clock reading returns False for both rows. A filter can therefore lose the matching row without an error.
  3. Localize the intended cutoff. Localizing midnight to Asia/Kolkata gives an instant at 18:30 UTC on the previous date. This identifies the cutoff rather than shifting the stored UTC logins.
  4. Read the two comparisons. 15:35 UTC is before the cutoff and 18:40 UTC is after it, so the mask is True, False. Localizing the matching clock reading to UTC also makes equality match the first login.

Key idea

Give a naive cutoff its intended zone before ordering or testing equality against aware timestamps.

Checkpoint

Check: Aware and naive comparisons

  1. Question 1 of 2 Which aware-versus-naive comparison fails loudly in the recorded example?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Ordering with less-than

    Do not rely on an equality filter to detect an unresolved cutoff clock.

  2. Question 2 of 2 Midnight on the next IST date is 18:30 UTC. Is a login at 18:40 UTC before that cutoff?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: No, it is ten minutes after

    Localize the intended IST cutoff, then compare it with the aware UTC values.

Practise daily users in IST

The exercise runs in the browser with only the standard library, which is enough here: IST is a fixed offset, so datetime.timezone(timedelta(hours=5, minutes=30)) converts every moment in this exercise exactly. Its inputs use modern IST, not the historical offset changes in the IANA database.

Exercise · Easy · Python

Count daily users and the busiest hour in IST

An app writes one event per login: a user id and the moment of the login in UTC, as text such as "2026-10-04T18:45:00Z". Some older events carry an offset instead, such as "2026-10-05T00:15:00+05:30". Write two functions in daily_users.py:

  • daily_active_users(events): how many different users logged in on each IST date, as a dictionary from the date in YYYY-MM-DD form to the count, with the dates in ascending order;
  • peak_hour(events): the IST hour, from 0 to 23, with the most logins. When two hours have the same count, return the earlier one.

events is a list of (user_id, moment) pairs with at least one pair. Use only the standard library: IST is UTC+05:30 all year, with no daylight saving, so a fixed offset converts every modern event instant in this exercise exactly. The input dates follow this modern-IST contract; historical records with different offsets require the named zone's rules.

Starter code · daily_users.py

from datetime import datetime, timedelta, timezone

IST = timezone(timedelta(hours=5, minutes=30))


def daily_active_users(events):
    """Different users per IST date: {"2026-10-04": 7, ...}, dates in ascending order.

    events is a list of (user_id, moment) pairs, such as ("u01", "2026-10-04T18:45:00Z").
    """
    # Replace this line with your code.
    return {}


def peak_hour(events):
    """The IST hour (0-23) with the most logins; the earlier hour wins a tie."""
    # Replace this line with your code.
    return 0
The sample tests · test_daily_users.py
from daily_users import daily_active_users, peak_hour

WEEKEND = [
    ("u01", "2026-10-03T03:10:00Z"),
    ("u02", "2026-10-03T06:55:00Z"),
    ("u03", "2026-10-03T15:40:00Z"),
    ("u04", "2026-10-03T16:05:00Z"),
    ("u01", "2026-10-03T19:20:00Z"),
    ("u05", "2026-10-03T20:45:00Z"),
    ("u02", "2026-10-04T02:30:00Z"),
    ("u06", "2026-10-04T05:15:00Z"),
    ("u03", "2026-10-04T15:35:00Z"),
    ("u07", "2026-10-04T15:50:00Z"),
    ("u04", "2026-10-04T16:20:00Z"),
    ("u08", "2026-10-04T18:40:00Z"),
    ("u05", "2026-10-04T19:05:00Z"),
    ("u09", "2026-10-04T22:30:00Z"),
]


def test_counts_by_ist_date():
    """counts the users of each IST date, after converting from UTC"""
    assert daily_active_users(WEEKEND) == {"2026-10-03": 4, "2026-10-04": 7, "2026-10-05": 3}


def test_dates_in_ascending_order():
    """returns the dates in ascending order, whatever the order of the events"""
    assert list(daily_active_users(list(reversed(WEEKEND)))) == ["2026-10-03", "2026-10-04", "2026-10-05"]


def test_offsets_and_the_midnight_boundary():
    """reads +05:30 offsets as well as Z, and puts 18:30 UTC on the next IST date"""
    events = [
        ("a", "2026-10-05T00:15:00+05:30"),
        ("a", "2026-10-04T18:45:00Z"),
        ("b", "2026-10-04T18:29:59Z"),
        ("c", "2026-10-04T18:30:00Z"),
    ]
    assert daily_active_users(events) == {"2026-10-04": 1, "2026-10-05": 2}


def test_peak_hour_in_ist():
    """finds the busiest hour on the IST clock, not the UTC one"""
    assert peak_hour(WEEKEND) == 21


def test_peak_hour_tie():
    """returns the earlier hour when two hours have as many logins"""
    events = [
        ("a", "2026-10-04T13:40:00Z"),
        ("b", "2026-10-04T02:31:00Z"),
        ("c", "2026-10-04T13:31:00Z"),
        ("d", "2026-10-04T02:45:00Z"),
    ]
    assert peak_hour(events) == 8
A hint

Turn each moment into an aware datetime first: datetime.fromisoformat(moment) reads both Z and +05:30, and .astimezone(IST) moves it to the IST clock. Then .date().isoformat() gives the key for the first function and .hour the key for the second. Keep a set of user ids per date so that a user who logs in twice counts once.

The sample tests run on this device, in your browser (Pyodide): nothing is sent to mysmartcopilot.com. The first run downloads Python (about 13.5 MB), which is kept for the next runs. A check in your browser is feedback for you, not proof that the code is right for every input.

Practice that adapts to you

Practise this lesson

14 questions about 7 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.

  1. Question 1 of 14 What does a trailing Z say about a logged timestamp?

    Choose one answer.

    Show the answer: Question 1 of 14

    Answer: It names UTC

    Use the source's actual offset or zone, rather than treating all strings as local clocks.

  2. Question 2 of 14 A column holds naive times written on a modern IST till clock. Which call attaches their intended zone?

    Choose one answer.

    Show the answer: Question 2 of 14

    Answer: times.dt.tz_localize("Asia/Kolkata")

    Localize a known naive source clock; convert an instant whose zone is already known.

  3. Question 3 of 14 Which order computes daily users on the IST clock from aware UTC logins?

    Choose one answer.

    Show the answer: Question 3 of 14

    Answer: Convert each login, take its date, then count distinct users

    Conversion belongs before the grouping key is extracted.

  4. Question 4 of 14 A login is stored as 19:20 UTC on Saturday. When does it happen on the modern IST clock?

    Choose one answer.

    Show the answer: Question 4 of 14

    Answer: Sunday at 00:50

    19:20 + 05:30 = 00:50 on the next date. The exact 18:30 UTC boundary also belongs to that next IST date.

  5. Question 5 of 14 What kind of values does dt.date return in this lesson?

    Choose one answer.

    Show the answer: Question 5 of 14

    Answer: Python date objects without a time zone

    A date alone omits the time and zone, even when the source column is aware.

  6. Question 6 of 14 A report needs the earlier of two timestamps whose month order differs from their leading day-number order. Which stored key should decide?

    Choose one answer.

    Show the answer: Question 6 of 14

    Answer: The original datetime values

    Compute with typed values and create human-readable labels only after the time ordering.

  7. Question 7 of 14 Which operation turns a Timedelta into a number of minutes?

    Choose one answer.

    Show the answer: Question 7 of 14

    Answer: Divide by pd.Timedelta(minutes=1)

    Components describe parts of a normalized duration; dividing by a unit measures the entire duration.

  8. Question 8 of 14 A UTC session starts at 23:50 and ends at 00:20 the next date. How long is it?

    Type a number.

    Show the answer: Question 8 of 14

    Answer: 30 minutes

    Ten minutes reach midnight and twenty more reach 00:20, giving 30 elapsed minutes.

  9. Question 9 of 14 How many elapsed hours does the spring clock-change Sunday last in Europe/London?

    Type a number.

    Show the answer: Question 9 of 14

    Answer: 23 hours

    The local clock skips one hour between midnight and the next midnight.

  10. Question 10 of 14 A London report promises 08:00 local time each day across the spring change. Which step preserves the promise in pandas 3?

    Choose one answer.

    Show the answer: Question 10 of 14

    Answer: A calendar-day step in Europe/London, then conversion to UTC

    Keep a civil schedule in its named zone and use UTC instants for execution.

  11. Question 11 of 14 Which accessor numbers Sunday as 0?

    Choose one answer.

    Show the answer: Question 11 of 14

    Answer: DuckDB's dayofweek

    The three engines share date meanings but not every ordinal numbering convention.

  12. Question 12 of 14 A raw DuckDB dayofweek filter uses value < 5 for Monday-to-Friday workdays. What does it get wrong?

    Choose one answer.

    Show the answer: Question 12 of 14

    Answer: It includes Sunday and excludes Friday

    State the desired weekdays or normalize to ISO numbers before applying a weekday threshold.

  13. Question 13 of 14 An aware UTC column is ordered against a naive Timestamp. What should the caller resolve?

    Choose one answer.

    Show the answer: Question 13 of 14

    Answer: The naive timestamp's intended zone

    A named-zone localization resolves a known naive clock; changing display labels does not.

  14. Question 14 of 14 A naive Timestamp has the first UTC login's clock reading. What does equality with the aware UTC column return in the recorded example?

    Choose one answer.

    Show the answer: Question 14 of 14

    Answer: A Series of False values, without an error

    This silent result is why equality must not substitute for resolving the timestamp's zone.

Interview questions

Why should an application store timestamps in UTC and convert them to IST only when it shows or groups them? (warm-up)

A UTC timestamp names one moment without ambiguity: it never jumps for daylight saving, and every server, database and country reads it the same way. A clock reading without its zone could be IST, UTC or London time, and zones with daylight saving skip an hour every spring and repeat one every autumn. Storing UTC keeps arithmetic, sorting and joins correct, and lets each report choose its own zone from the same column: a team in India groups by the IST date, a team in London by the London date. In pandas, parse with utc=True, keep the column aware, and call dt.tz_convert("Asia/Kolkata") just before taking the date or the hour, because the IST date of any moment after 18:30 UTC is the next day.

What is the difference between tz_localize and tz_convert in pandas? (warm-up)

tz_localize attaches a zone to naive timestamps and keeps their clock reading: 09:00 becomes 09:00 IST, which pandas now knows to be 03:30 UTC. tz_convert moves aware timestamps to another zone and keeps the moment: 03:30 UTC becomes 09:00 IST, the same instant on another clock. Localize answers “which clock wrote this?”, convert answers “what does this moment read elsewhere?”. With a named zone argument, each refuses the other kind of data: tz_convert on naive values and tz_localize on aware ones raise a TypeError. Passing None has a different purpose: localization removes the zone while keeping the clock reading; conversion to None first puts the instant in UTC and then removes the zone. Localizing can also fail in zones with daylight saving, where a time in the skipped hour does not exist and one in the repeated hour is ambiguous; pass nonexistent= or ambiguous= to decide. IST has no such hours.

Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.

  1. Fresher to mid

    Daily active users on your dashboard differ from the product team's figures by up to 9 % on some days, although both read the same login table. The table stores UTC times and the team reports in IST. How do you find and fix the cause?

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. Mid to senior

    A daily report must reach users in Mumbai and in London at 09:00 their time. After the UK clocks change in March, the London report arrives an hour late. Explain why, and how you would compute the send times with pandas.

    Model answer, Pro. First step and follow-ups

Key takeaways

  • Keep timestamps aware and in UTC; convert with dt.tz_convert("Asia/Kolkata") just before you take the date or the hour.
  • Every moment after 18:30 UTC belongs to the next IST date, and IST’s half-hour offset means hourly UTC tables cannot be relabelled as IST hours.
  • tz_localize names the zone of naive clock readings; tz_convert changes the clock of aware moments.
  • In pandas 3, Day(1) is a calendar day and Timedelta(hours=24) is 24 hours: they differ where clocks change.
  • Weekday numbers differ: Sunday is 6 in pandas, 7 in polars and in ISO numbering, and 0 in DuckDB’s dayofweek.
  • Ordering aware against naive values raises a TypeError, but == silently returns False.

Terms in this lesson

aware timestamp
A timestamp whose time zone and UTC offset identify its clock reading as a specific instant.
naive timestamp
A clock reading with no time zone attached. It does not by itself identify which UTC instant the clock meant.

Corrections

  • Timestamp precision follows the input; named-zone localization and the modern fixed-offset scope are explicit.
  • Naive source-clock meaning is demonstrated separately from UTC coercion; elapsed durations and ISO year boundaries have concrete examples.

References

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.