Knowledge base / Python
pandas to_datetime: date formats, errors and time zones
I convert one column while keeping rejected records visible. Input format, time zone and storage resolution are separate decisions, and each needs an explicit rule.

Dates can look plausible long after their meaning has drifted away from the report author’s assumptions. The string 01/06/2024 permits two familiar interpretations. A number may represent seconds, milliseconds or an identifier. A clock reading without a time zone does not locate the event. I would settle those questions before asking a parser to convert anything.
pd.to_datetime() converts inputs into date and time values supported by pandas. Below, I use the pandas 3.1 documentation and small synthetic examples. I explain the result separately from the interpretation rule. I also discuss output resolution, whose defaults changed between library versions and can affect later analysis, rather than treating an old printed dtype as universal.
Establish the field’s meaning first
Imagine an order date column. Before parsing it, I would ask whether it represents creation time, an accounting day or a delivery deadline. Those are different facts. A valid calendar date does not establish that we assigned the correct meaning. In this exercise, the field means the day an order was placed, written in day, month, year order.
Keep the source text alongside the converted result. When something fails, you can then see whether the problem was an impossible day, a different separator or an unexpected description. Overwriting the input makes later investigation harder. Several distinct invalid strings can all become the same missing value, so the original is needed to understand why each record was rejected.
Record the expected range as well. If the report covers this year’s orders, a technically valid date from several decades ago still needs an explanation. Parsing checks whether an input can be interpreted. A business rule checks whether that interpretation is suitable for the application. One check cannot replace the other simply because both refer to the same date column.
An explicit format removes a major ambiguity
The to_datetime reference describes format as the expected date layout. I use %d/%m/%Y here. The codes represent day of month, month and a four-digit year; Python’s format code reference lists them in full. The separators in the pattern correspond to those in the incoming strings.
import pandas as pd
raw = pd.Series(
["01/06/2024", "02/06/2024", "31/02/2024", None],
index=["A", "B", "C", "D"],
)
parsed = pd.to_datetime(raw, format="%d/%m/%Y", errors="coerce")
A means 1 June and B means 2 June. C does not describe an existing day and becomes NaT. D was already missing and remains missing. With no hour provided, the valid results have a midnight time component. That is part of their representation, rather than evidence that a customer placed an order exactly at midnight. Preserve the distinction in any later explanation.
The documentation warns that dayfirst=True is a preference, rather than a strict rule. For a known source, I would specify the format. If the contract requires an identical character layout, including mandatory leading zeros, add a separate text validation rule. Successful parsing does not, by itself, guarantee that every character follows the exact visual pattern required by an external specification.
Choose between raise and coerce deliberately
The default errors="raise" stops conversion when an invalid value is encountered. That is reasonable when further calculations must wait for valid dates. In our example, 31/02/2024 causes an exception instead of a complete converted Series. I would avoid treating every such interruption as something to suppress. Sometimes stopping is precisely the behaviour the reporting process needs.
With errors="coerce", invalid parsing produces NaT. That lets you inspect problems together, but does not repair them. I would use it during an import inspection, with a visible count of rejected inputs. Filtering out every NaT later produces a report about a smaller population. The reader needs to know which part of the original material no longer contributes to the result.
Support for errors="ignore" was removed in pandas 3.0. I would no longer recommend it as a way to retain original text. Store the input separately and choose a response to the conversion result. Code using the old option needs to match the environment version instead of assuming that a historical example still describes the current API.
Separate missing inputs from conversion failures
C and D have the same NaT result but different histories. I want to distinguish them. Series.isna identifies missing values. Combining the before and after information isolates a newly rejected input. For our Series, use this mask:
invalid = raw.notna() & parsed.isna()
rejected = raw[invalid]
The rejected result contains only C, with 31/02/2024. D is absent from the new-failure list because it was already missing. That is a specific definition of this check. An empty string or a string containing spaces is different from an original None value. If the source uses such missing markers, define their normalisation separately and make that decision visible.
Avoid detecting NaT through an ordinary equality comparison. Use missing-value methods. In an import summary, I would show pre-existing missing values separately from new parsing failures. The two counts may lead to different conversations. A field might have been optional from the start, while a newly invalid date pattern could mean an integration changed its output without updating the agreed contract.
Mixed formats need a conscious policy
If part of a file uses day/month/year and another part uses year-month-day, first investigate why. Were two systems combined? Did an export format change halfway through the period? I would prefer separating known sources and their rules before inferring every row individually. That makes a rejected record easier to explain and connects its interpretation to evidence about its origin.
The current API offers format="mixed" and format="ISO8601" for appropriate inputs. The reference explicitly describes individual format inference as risky. Having that option does not resolve whether 01/06/2024 was meant to describe June. We still need source knowledge that cannot be obtained with certainty from this string alone, however confidently the parser can produce one possible date.
I would avoid trying formats repeatedly until no exceptions remain. That can accept a possible date with the wrong meaning. If several layouts are permitted, document how they are recognised and examine a case that fits more than one interpretation. That ambiguous record is a particularly valuable part of the exercise, because obvious cases can make an incorrect rule look reliable.
A numeric timestamp needs a unit
A Unix timestamp represents an offset from the Unix epoch. The API uses unit for the numeric unit and origin for the reference point. Small explicit values let us follow the result without calculating distant dates:
epoch_dates = pd.to_datetime(
[0, 86400], unit="s", origin="unix", utc=True
)
Zero represents midnight UTC on 1 January 1970. There are 86,400 seconds in a day, so the second value represents midnight UTC on 2 January. If the input numbers meant milliseconds, interpreting them as seconds would produce a different instant. The unit needs to come from the source contract. Choosing whichever option makes a result look familiar is an unreliable substitute.
A number resembling a calendar date is not automatically an epoch offset. A numeric year-month-day code needs another interpretation. In pandas 3.1, passing numeric values together with format is deprecated; establish a text representation for dates encoded as digits. Excel serial dates also have their own convention. They should not automatically receive the Unix origin merely because their cells contain numbers.

UTC and a local clock reading are different inputs
If a string includes an offset, such as 2024-01-02T10:00:00+01:00, utc=True converts it to UTC. The result represents 09:00 UTC on the same day. With a string lacking time zone information, the same option assigns UTC instead. It does not infer the location of the computer, customer or file author. That difference matters when combining data from several sources.
For naive values known to represent Warsaw local time, I would parse first and assign the zone afterwards. tz_localize preserves the clock reading while attaching a zone. tz_convert changes the representation of an already established instant to another zone.
local_raw = pd.Series(["2024-01-02 10:00"])
local_dates = pd.to_datetime(local_raw, format="%Y-%m-%d %H:%M")
aware_dates = local_dates.dt.tz_localize("Europe/Warsaw")
utc_dates = aware_dates.dt.tz_convert("UTC")
On this winter date, local 10:00 corresponds to 09:00 UTC. Around daylight saving changes, a local time can be ambiguous or nonexistent. Localisation has separate ambiguous and nonexistent options, both reporting a problem by default. I would agree a policy with the data owner. Automatically shifting or inferring a value can change how events are interpreted and ordered, so it deserves an explicit decision.
Input units do not guarantee the output dtype
The pandas 3.0 notes describe inferring datetime resolution instead of broadly forcing nanoseconds. Pandas 3.1 changed the default for numeric input again: the result generally uses microseconds even when unit=“s” describes the input. An old printed datetime64[ns] result is therefore not a universal test of whether a conversion is correct.
In our epoch example, unit=“s” tells pandas how to interpret 86400. It does not promise that the internal result will use exactly the same resolution. I would separate those decisions in the import documentation. When moving code between versions, inspect assumptions in later steps, especially any operation converting date values into raw integers and relying on a particular scale.
Storage resolution is also different from measurement accuracy. An order date known only to the day does not become a microsecond observation after conversion. If a downstream contract needs a particular output unit, the documentation points to as_unit. Choose that unit deliberately. I would avoid manually multiplying numbers simply because old code assumed that every datetime value was stored in nanoseconds.
The return type depends on the input
A valid scalar string can produce a Timestamp, a list a DatetimeIndex, and a Series a date Series retaining its index. These differences affect later operations. For a Series, the dt accessor provides operations on date values. Naming a variable date_series does not give a list Series behaviour. The actual object returned by conversion matters more than the name you chose for it.
You can also assemble dates from a table with year, month and day fields. In that mode, format does not control the table’s interpretation. It is a different input path documented by the API. I would keep it separate from parsing a text column, so that a reader does not try to repair incorrectly named date components by adding another format pattern.
When attaching results to a table, preserve index alignment. Avoid accidentally changing row order between selecting a column and assigning its converted dates. In the exercise, identifiers A through D make the origin of each result easy to follow. A larger import needs an equally understandable identifier when someone later asks about a particular rejected record or an unexpected date in the report.
Prepare the result for analysis and handover
Before grouping, I would inspect row counts, missing counts and the range of valid dates. Compare several results with their original text, particularly ambiguous dates and period boundaries. Inspecting only cases such as the thirteenth day of a month can hide a day-month reversal: some incorrect interpretations are impossible in those records, while early-month days can be silently swapped and still look valid.
Keep values as dates while sorting, filtering and calculating. Leave text formatting to presentation, following the pandas time series guide. The visible appearance of a date should not decide whether it remains an appropriate type for analysis. A readable string and a correctly typed value are separate parts of the solution and serve different purposes in the process.
At handover, state the source format, time zone, missing-value policy and library version. Add a condition for reviewing the rule when the export changes. The next person can then understand why the conversion was chosen. A bare code fragment can continue to run successfully after an input change while interpreting some records differently from the original agreement. The surrounding contract makes that change easier to detect.
Include the whole reporting month
Filtering usually follows conversion. For timestamped events, I would use an interval from the start of June inclusive to the start of July exclusive. This includes events late on the final June day. Ending a condition at midnight on 30 June can omit almost that entire day, even though the month in the boundary looks superficially correct.
in_june = (parsed >= pd.Timestamp("2024-06-01")) & (
parsed < pd.Timestamp("2024-07-01")
)
june_dates = parsed[in_june]
In our Series, A and B enter the result. C and D have no date establishing membership in June. I would still show them separately as a coverage limitation. Excluding them through a filter does not explain which month they actually belonged to or whether their absence could change the reader’s decision. Keep that unresolved part visible beside the valid result.
Boundaries must also match the time zone of the values. The fragment above concerns our naive example. For instants stored in UTC, decide whether the reporting month is a UTC month or the reader’s local month. I would avoid removing time zone information merely to make an incompatible comparison stop failing. Resolve the meaning of the period first, then construct compatible boundaries.
A calendar day and an event instant serve different purposes
A date of birth, accounting day or delivery deadline may represent a day without an event time. Attaching midnight is a convenient representation rather than newly obtained information about an instant. I would avoid automatically converting such a day between time zones. Moving midnight could change the calendar day, even though the original day was precisely the fact we needed to preserve.
An execution log may instead require an exact instant. Omitting the zone then makes comparison across systems harder. Recognise the field type before parsing. Identical strings in two tables can need different rules because they describe different parts of a process. Shared visual formatting does not establish shared meaning, and one universal conversion policy can hide that distinction.
When combining sources, ask about business dates too. A store may assign overnight events to the previous operational shift. Type conversion alone cannot derive that rule. Agree and document it separately from the system timestamp. The report can then show the intended period while preserving the original event time for investigation and allowing another person to reconstruct how the business date was assigned.
Return rejected records with context
A list of invalid strings becomes more useful with a record identifier and the expected rule. Here, I would flag C with its impossible February date and describe D as an existing absence. I would avoid assigning both the same cause automatically. The source owner needs to know whether to correct a value, supply a missing field or explain why the information was optional.
After receiving corrections, apply the same conversion rule and inspect which cases are resolved. Preserve their relationship to the source rather than manually inserting a date with no origin recorded. For a recurring import, agree a response threshold for new failures. That threshold should reflect the field’s importance to the report, rather than the convenience of making an error message disappear.
An exercise before the next import
Prepare five inputs: a valid day, an ambiguous date, an impossible day, a missing value and a clock reading with a UTC offset. Write down the intended meaning of each before choosing parameters. Then separate inputs that genuinely share a contract. Avoid trying to reconcile conflicting source rules with one magical parser option that appears to accept everything.
Finally, explain which records remain in the report and what happens to rejected values. If type conversion itself is new to you, see pandas astype. I would consider the import ready when I can explain both the converted dates and the meaning and treatment of the values that did not make it through.
Key takeaways
Does errors='ignore' still work in pandas?
Support was removed in pandas 3.0. Current choices are raise and coerce. To preserve input material, keep it in a separate column and inspect the conversion result.
Can dayfirst=True replace an explicit format?
It is a preference rather than strict format validation. If the source format is known, specify it, for example format='%d/%m/%Y', and inspect rejected cases.
Does utc=True recognise a local Warsaw time automatically?
No. It assigns UTC to an input without a time zone and converts an offset-aware input to UTC. For a naive local clock reading, first establish its time zone and use tz_localize.
AI was used in an automated way while working on this article. If you want to learn how to do it too, check out this project.
