pd.to_datetime
pd.to_datetime(df["col"]) converts strings or numbers into datetime64 values, after which the .dt accessor exposes parts such as .dt.year, .dt.month and .dt.day_name(). Pass format="%d/%m/%Y" for an explicit layout and errors="coerce" to turn unparseable values into NaT.
Syntax
pd.to_datetime(arg, format=None, errors="raise", dayfirst=False, utc=False, unit=None)| Part | What it is |
|---|---|
format | strftime pattern such as "%Y-%m-%d" or "%d/%m/%Y %H:%M"; faster and unambiguous |
errors | "raise" (default) or "coerce" to set invalid values to NaT |
dayfirst | True to read 03/04/2024 as 3 April |
unit | "s" or "ms" when converting Unix timestamps |
Examples
import pandas as pd
df = pd.DataFrame({"order_date": ["2024-03-15", "2024-03-16", "2024-04-02"]})
df["order_date"] = pd.to_datetime(df["order_date"])
df["order_date"].dt.month.tolist()Result: [3, 3, 4]
df["weekday"] = df["order_date"].dt.day_name()
df["ym"] = df["order_date"].dt.strftime("%Y-%m")
dfResult: order_date weekday ym 0 2024-03-15 Friday 2024-03 1 2024-03-16 Saturday 2024-03 2 2024-04-02 Tuesday 2024-04
pd.to_datetime(pd.Series(["15/03/2024", "bad"]), format="%d/%m/%Y", errors="coerce")Result: 0 2024-03-15 1 NaT dtype: datetime64[ns]
Common mistakes
- Day and month swapped: ambiguous dates like 03/04/2024 are read month-first; pass format or dayfirst=True.
- AttributeError: Can only use .dt accessor with datetimelike values: the column is still text; run pd.to_datetime first.
- ValueError on one bad row stops the whole conversion: use errors="coerce" and inspect the NaT rows afterwards.
Practice pd.to_datetime
These drills check your answer on live data, free, no account needed.
- Dates with to_datetime and dtThe `joined` column holds dates as text. Return a DataFrame with the columns `user`, `month` (the month number) and `weekday` (the full day name, like Monday).
Questions
How do I extract the year and month into columns?
df["year"] = df["d"].dt.year and df["month"] = df["d"].dt.month. For a period label use df["d"].dt.to_period("M").
How do I compute the difference between two dates?
Subtracting two datetime columns gives a timedelta; (df["end"] - df["start"]).dt.days returns whole days.
How do I parse dates while reading a CSV?
pd.read_csv(path, parse_dates=["order_date"]) converts the column during loading.
Related
- resampleHow to resample a time series in pandas: monthly, weekly or daily buckets with sum or mean, upsample with ffill, use a date column with on, and new aliases.
- astypeHow to change a column type in pandas with astype and pd.to_numeric: text to numbers, float to int, strings, categories, nullable Int64, bad values and NaN.
- pd.read_csvHow to read a CSV file in pandas with pd.read_csv: separators, headers, index columns, parsing dates, selecting columns, dtypes and the errors people hit.
- shift and diffHow to use shift and diff in pandas to get the previous or next row, compute the change and percent change between periods, and lag within groups.