Sub topic 6
Parsing strings with UTC offsets
Real data often arrives as text such as 2024-06-01T00:00:00+02:00. This chapter covers how pd.to_datetime turns such strings into time zone-aware values, what goes wrong when the offsets differ, and how to produce one consistent column. It assumes you know the difference between naive and aware timestamps. It also assumes you can use tz_localize and tz_convert from the earlier chapters and read basic ISO 8601 date strings.
What an offset in a string tells you
An offset such as +02:00 says how far the local clock is from UTC at that moment. It identifies one instant exactly. It does not say which place the timestamp came from.
+01:00could be Berlin in winter, Lagos all year, or Casablanca during some periods.2024-06-01T00:00:00+02:00and2024-05-31T22:00:00Zare the same instant written two ways.- The suffix
Zmeans UTC, an offset of zero.
An offset is a fixed shift. An IANA name such as Europe/Berlin is a set of rules that changes the shift over the year. A string with an offset gives you the first and never the second. After parsing, you can convert to a named zone, but you must know the zone from somewhere else.
Parsing with utc=True
When the strings carry different offsets, pass utc=True. pandas converts every value to UTC and returns one tz-aware result.
import pandas as pd
raw = ["2024-01-01T00:00:00+01:00", "2024-06-01T00:00:00+02:00"]
parsed = pd.to_datetime(raw, utc=True)
print(parsed) # 2023-12-31 23:00:00+00:00 and 2024-05-31 22:00:00+00:00
print(parsed.tz) # UTCThe result has dtype datetime64[ns, UTC] (the time unit can differ in newer pandas versions). Each value is the same instant as its input string. Only the display changed.
What happens without utc=True
The outcome depends on whether the offsets match.
| Input strings | Result without `utc=True` |
|---|---|
| All have the same offset, for example `+01:00` | A tz-aware column with a fixed-offset zone |
| All end in `Z` | A tz-aware UTC column |
| Different offsets | Older pandas returns an object column of Python `datetime` objects. Newer versions warn about it first and then raise an error |
| No offsets at all | A tz-naive column |
The object-column case is the dangerous one. The values look fine when printed, but the column has no datetime dtype. The .dt accessor fails on it, resample fails, and comparisons run slowly one value at a time.
import pandas as pd
same = pd.to_datetime(["2024-01-01T00:00:00+01:00", "2024-06-01T00:00:00+01:00"])
print(same.tz) # a fixed +01:00 zone, not Europe/Berlin or any other named zoneA fixed-offset zone never adjusts for daylight saving time (DST). Adding a day to a value in such a column never changes the offset, even if the original data came from a place that observes DST. Use tz_convert to move to a named zone before doing calendar arithmetic.
Naive strings mixed with offset strings
With utc=True, strings that have no offset are assumed to already be in UTC. They are not interpreted as local time.
import pandas as pd
raw = [
"2024-01-01T12:00:00", # no offset
"2024-01-01T12:00:00+02:00", # offset given
"2024-01-01T12:00:00Z", # UTC marker
]
parsed = pd.to_datetime(raw, utc=True, format="ISO8601")
print(parsed)
# 12:00 UTC, 10:00 UTC, 12:00 UTCThe first and third values come out identical. If the naive strings are really New York local times, this result is wrong by four or five hours and nothing warns you. When a source mixes naive and offset strings, split them by pattern. Then parse and localize each group on its own.
The format="ISO8601" argument tells pandas to accept any ISO 8601 variant for each element. Without it, newer pandas guesses one format from the first string and raises an error if a later string does not match.
Choosing a format explicitly
Not every source uses ISO 8601. The %z directive in a format string reads an offset such as +0530 or +05:30.
import pandas as pd
raw = ["2024-03-10 12:00:00 +0530", "2024-03-10 12:00:00 -0800"]
parsed = pd.to_datetime(raw, format="%Y-%m-%d %H:%M:%S %z", utc=True)
print(parsed)
# 2024-03-10 06:30:00+00:00 and 2024-03-10 20:00:00+00:00An explicit format is also faster than guessing, and it fails loudly when a row does not match. Time zone abbreviations such as EST or IST are a poor basis for parsing. IST can mean India, Israel, or Ireland, and %Z does not handle most abbreviations. If your strings contain abbreviations, strip them and call tz_localize with an explicit IANA name.
Bad rows
By default, one unparseable string raises an error. Use errors="coerce" to turn bad values into NaT (not a time), then inspect them.
import pandas as pd
s = pd.Series([
"2024-01-01T00:00:00+01:00",
"not a date",
"2024-06-01T00:00:00+02:00",
])
parsed = pd.to_datetime(s, utc=True, errors="coerce", format="ISO8601")
print(parsed)
print(s[parsed.isna()]) # the rows that failedDo not coerce and move on without looking. Count the NaT values before and after parsing, so a changed export format does not quietly turn a whole column into missing data.
From parsed UTC to local time
Parsing with utc=True gives you one clean instant for each row. A second step puts it in the zone your analysis needs. The earlier tz_convert rules apply: use the .dt accessor on a Series.
The next example reads a small CSV and compares UTC dates with New York dates.
import io
import pandas as pd
csv = (
"event,ts\n"
"login,2024-03-10T04:15:00+00:00\n"
"logout,2024-03-09T23:30:00-05:00\n"
)
df = pd.read_csv(io.StringIO(csv)) # ts is plain text here
df["ts"] = pd.to_datetime(df["ts"], utc=True)
df["ts_ny"] = df["ts"].dt.tz_convert("America/New_York")
df["day_utc"] = df["ts"].dt.date
df["day_ny"] = df["ts_ny"].dt.date
print(df[["event", "day_utc", "day_ny"]])
print(df.loc[1, "ts"] - df.loc[0, "ts"]) # 0 days 00:15:00Both events fall on 2024-03-10 in UTC. In New York both fall on 2024-03-09, because the clock there was still on standard time (-05:00) at that hour. The subtraction works because both values are aware. The 15-minute gap is the real elapsed time, whichever zone you display.
The example leaves parse_dates out of read_csv on purpose. With mixed offsets, read_csv leaves the column as text or objects. Reading as text and calling to_datetime afterwards gives you control over utc=True and errors.
A decision path
Common errors
- Object column from mixed offsets. Symptom:
AttributeError: Can only use .dt accessor with datetimelike values. Fix: re-parse the original strings withutc=True. - Assuming a fixed offset is a zone. Symptom: values from a DST region stay at the same offset across the DST change. Fix:
tz_convertto a named zone. - Naive strings treated as UTC. Symptom: local-time rows are shifted by the zone offset. Fix: parse those rows without
utc=Trueand usetz_localizewith the right zone name. - Guessing formats on irregular data. Symptom: an unexpected error halfway through a column, or some rows parsed with day and month swapped. Fix: pass an explicit
format, orformat="ISO8601"for ISO data. - Silent coercion. Symptom: unexplained missing values after
errors="coerce". Fix: checkparsed.isna().sum()against the number of missing values in the source. - Calling tz_localize on already-aware data. Symptom:
TypeErrorsaying the index is already tz-aware. Fix: usetz_convertto change zone. Usetz_localize(None)only when you want to drop the zone, a step covered in the chapter on removing time zones.
Exercise
The strings ["2024-11-03T05:30:00Z", "2024-11-03T06:30:00Z"] are parsed with utc=True and converted to America/New_York. What local wall-clock times and offsets do you expect, and why do the two results have the same hour on the clock but different offsets?
Show answer
05:30 UTC becomes 01:30 -04:00 (EDT, the first occurrence), and 06:30 UTC becomes 01:30 -05:00 (EST, the second occurrence), because clocks in New York fell back from 02:00 EDT to 01:00 EST on 2024-11-03. The UTC strings are exactly one hour apart and identify distinct instants. Converting from UTC never raises an ambiguity error, because each UTC instant maps to exactly one local time. Ambiguity only appears when you go the other way with tz_localize.
Exercise
A CSV column holds "2024-05-01T10:00:00+02:00", "2024-05-01T10:00:00" and "2024-05-01T10:00:00Z". After pd.to_datetime(col, utc=True, format="ISO8601"), which two results are equal, and what mistake could this hide if the middle string was recorded in Paris local time?
Show answer
The second and third results are equal, both 2024-05-01 10:00:00+00:00, because utc=True treats a string without an offset as UTC. If the middle string was really Paris local time (+02:00 in May), it is wrong by two hours and no error is raised. Fix it by parsing that group without utc=True and calling tz_localize("Europe/Paris") before converting to UTC.
Exercise
You parse ["2024-01-15T09:00:00+01:00", "2024-07-15T09:00:00+01:00"] without utc=True. Both strings carry the same offset, so you get a tz-aware column. Why is it risky to treat this column as Europe/Berlin time, and how would you get correct Berlin times?
Show answer
The column has a fixed +01:00 zone, which is not Berlin. Berlin uses +02:00 in July, so the July value is one hour off Berlin's real wall-clock time. To get correct Berlin local times, parse with utc=True (or keep the fixed offset, which is already one exact instant) and then call tz_convert("Europe/Berlin"). The July value then displays as 10:00+02:00 and the January value stays at 09:00+01:00.