TExcelTAD

Dates, Times and Units

Two columns can hold the same kind of value and still disagree: 03/04/2026 is 3 April in Hanoi and March 4 in Chicago, 14:00 in a Tokyo log is 05:00 UTC, and 72 in a weight column might be kilograms or pounds. Data Consistency showed how to detect these mismatches. Here you fix them, with three rules:

  1. Parse with an explicit format, per source, never by letting the library guess.
  2. Store one canonical form: timestamps as timezone-aware UTC, quantities in one unit per column, with the unit in the column name (weight_kg).
  3. Keep the original column (or file) until the conversion is checked, and log the rule.

Dates: one format per source

pd.to_datetime without a format guesses, and when the day is 12 or less, a day-first and a month-first reading are both valid. A silent wrong guess moves events by months. If you know which system wrote which rows, parse each part with its own format:

python · try it yourself
import pandas as pd

events = pd.DataFrame({
    "source": ["eu_app", "eu_app", "us_web", "us_web", "api", "api"],
    "when":   ["03/04/2026 14:05", "25/12/2026 09:00", "03/04/2026 2:05 PM",
               "12/25/2026 9:00 AM", "2026-04-03T14:05:00+07:00", "2026-12-25T02:00:00Z"],
})
formats = {"eu_app": "%d/%m/%Y %H:%M", "us_web": "%m/%d/%Y %I:%M %p"}
zones = {"eu_app": "Europe/Berlin", "us_web": "America/Chicago"}

parts = []
for source, rows in events.groupby("source", sort=False):
    if source == "api":
        ts = pd.to_datetime(rows["when"], format="ISO8601", utc=True)   # carries its own offset
    else:
        ts = pd.to_datetime(rows["when"], format=formats[source])       # naive local time
        ts = ts.dt.tz_localize(zones[source]).dt.tz_convert("UTC")
    parts.append(ts)
events["when_utc"] = pd.concat(parts)
print(events[["source", "when_utc"]].to_string(index=False))
source                  when_utc
eu_app 2026-04-03 12:05:00+00:00
eu_app 2026-12-25 08:00:00+00:00
us_web 2026-03-04 20:05:00+00:00
us_web 2026-12-25 15:00:00+00:00
   api 2026-04-03 07:05:00+00:00
   api 2026-12-25 02:00:00+00:00

The same text 03/04/2026 became 3 April for the European app and 4 March for the US site, because each source got its own format. Converting to UTC also reveals what the local clocks hide: 14:05 in Berlin on 3 April is 12:05 UTC (summer time, +2 h), while 14:05 in Hanoi (+07:00) is 07:05 UTC. Only on a single UTC timeline can you sort events, compute durations and split by time correctly.

Tip: Keep the timezone of the place as a separate column if behaviour depends on local time (shops open at 9 local time everywhere). Date and Time Features derives hour, weekday and holidays from local time, while ordering and splitting use UTC.

Daylight-saving traps

A naive local timestamp can be ambiguous (the hour repeated when clocks go back) or non-existent (the hour skipped in spring). tz_localize raises an error by default for both, which is the right default for cleaning: decide explicitly with ambiguous= and nonexistent= and count how many rows were affected.

Units: convert to one per column

A unit mismatch often shows up as two clusters in a histogram. Fix it with an explicit unit column when the source provides one, and with a documented rule when it does not:

python · try it yourself
import pandas as pd

patients = pd.DataFrame({
    "clinic":   ["A", "A", "B", "B", "C", "C"],
    "weight":   [72.0, 81.5, 165.0, 198.4, 70.2, 64000.0],
    "w_unit":   ["kg", "kg", "lb", "lb", "kg", "g"],
    "height":   [1.78, 1.69, 70.0, 74.0, 172.0, 160.0],
    "h_unit":   ["m", "m", "in", "in", "cm", "cm"],
})
to_kg = {"kg": 1.0, "g": 0.001, "lb": 0.45359237}
to_m = {"m": 1.0, "cm": 0.01, "in": 0.0254}

clean = pd.DataFrame({"clinic": patients["clinic"]})
clean["weight_kg"] = (patients["weight"] * patients["w_unit"].map(to_kg)).round(1)
clean["height_m"] = (patients["height"] * patients["h_unit"].map(to_m)).round(3)
clean["bmi"] = (clean["weight_kg"] / clean["height_m"] ** 2).round(1)
assert clean[["weight_kg", "height_m"]].notna().all().all(), "unknown unit"
print(clean.to_string(index=False))
clinic  weight_kg  height_m  bmi
     A       72.0     1.780 22.7
     A       81.5     1.690 28.5
     B       74.8     1.778 23.7
     B       90.0     1.880 25.5
     C       70.2     1.720 23.7
     C       64.0     1.600 25.0

After conversion every BMI is in a plausible adult range (22.7 to 28.5). Computed on the raw numbers, clinic B's patients would have looked absurdly heavy and short, and a model would have learned "clinic B" from the units instead of anything about the patients. The assert stops the script if a new unit appears that the mapping does not know, instead of producing NaN quietly.

When the unit is not recorded, you have to infer it. Do that with a rule you can defend (for example "adult weights above 140 in a clinic that documents pounds are pounds") and validate it with the data owner; Valid Ranges and Category Names shows how to flag values that fit neither interpretation.

Durations, numbers and decimal commas

Problem Example Fix
durations as text "1h 30m", "01:30:00", "90 min" pd.to_timedelta per pattern, store seconds
decimal comma "72,5" in a European export pd.read_csv(..., decimal=",", thousands=".") for the file, not a global replace
percent as text "12%" vs 0.12 strip %, divide by 100, name the column _share or _pct
Excel serial dates 45383 pd.to_datetime(x, unit="D", origin="1899-12-30")
epoch seconds vs milliseconds 1775210700 vs 1775210700000 magnitude tells you; unit="s" or unit="ms"
python · try it yourself
import pandas as pd

print(pd.to_datetime(45383, unit="D", origin="1899-12-30").date())
print(pd.to_datetime([1775210700, 1775210700000], unit="s", errors="coerce").tolist())
print(pd.to_datetime(1775210700000, unit="ms"))
print(pd.to_timedelta(["1h 30m", "01:30:00", "90min"]).total_seconds().tolist())
2024-04-01
[Timestamp('2026-04-03 10:05:00'), NaT]
2026-04-03 10:05:00
[5400.0, 5400.0, 5400.0]

The epoch value in milliseconds read as seconds would land some 56,000 years in the future, far beyond the year 2262 that pandas' nanosecond timestamps can represent, which errors="coerce" turns into NaT. Mixing seconds and milliseconds is a common logging bug; checking the magnitude (13 digits means milliseconds for present-day dates) catches it.

Pitfalls

  • Parsing the whole column with one guessed format: dayfirst=True fixes one source and breaks another. Parse per source.
  • Dropping the timezone: tz_localize(None) after converting makes later joins with other zones silently wrong.
  • Converting units by replaceing digits in strings: convert numbers with a factor table, and keep the factor table in the code and the log.
  • Rounding too early: convert at full precision, round only for display or at the end.

Practice

  1. A column duration contains "45", "1:10" and "2h". The documentation says plain numbers are minutes. Write the conversion to seconds.
Answer
python
import pandas as pd
d = pd.Series(["45", "1:10", "2h"])
plain = d.str.fullmatch(r"\d+")
sec = pd.Series(index=d.index, dtype="float64")
sec[plain] = d[plain].astype(int) * 60
sec[~plain] = pd.to_timedelta(d[~plain].where(~d[~plain].str.contains(":"), d[~plain] + ":00")).dt.total_seconds()
print(sec.tolist())   # [2700.0, 4200.0, 7200.0]

"1:10" is read as hours and minutes by appending ":00" seconds; check that interpretation with the data owner.

  1. Why should a training split by time use UTC rather than local timestamps from several countries?
Answer

Local timestamps from different zones are not on one timeline: an event at 10:00 in Tokyo happened before one at 08:00 in Berlin on the same day. A cut-off "train before 2026-06-01 00:00" in local time would put some later events in training and some earlier ones in the test set.

Test yourself

What does 03/04/2026 mean?

  1. 3 April 2026
  2. 4 March 2026
  3. It depends on the source's format, so it must be parsed with that source's explicit format
  4. Always ISO 8601

Which canonical form should timestamps from several systems be stored in?

  1. Local time of the server
  2. Timezone-aware UTC (plus the local zone as a separate column if needed)
  3. Strings in ISO format without offset
  4. Unix epoch in milliseconds without documentation

A weight column mixes kg, g and lb with a unit column. What is the safest conversion?

  1. Divide values above 100 by 2.2
  2. Multiply by a factor looked up from the unit column, and stop if a unit is unknown
  3. Drop the rows in lb
  4. Standardise the column, units cancel out