How do I clean dates and times in pandas?

Read mixed trade dates and find the ones pandas cannot read, turn dates into a year-month number for a monthly merge, assign trades to one-minute bars, and measure the time between trades.

After this lesson, you can read messy trade dates, match trades to a month and count trades per minute.

How do I find dates pandas cannot read?

pd.to_datetime(raw, format="mixed", errors="coerce") reads each date in whatever format it is written in and puts NaT, the missing date, where it cannot read the text. .isna() then finds those rows, here the text not a date.

The dates are a vendor’s made-up trade dates for one stock, written four ways, with month first in the slash date. A slash date such as 03/04/2026 can mean 4 March or 3 April, so a file with day first needs format="%d/%m/%Y" or dayfirst=True.

The following box reads the dates and lists the text that failed.

import pandas as pd

trades = pd.DataFrame({
    "raw_date": ["2026-03-04", "03/04/2026", "20260304", "March 4, 2026", "not a date"],
    "clock": ["09:00:13.250", "09:00:59.900", "09:01:02.000", "15:59:58.000", "16:00:00.000"],
})
trades["date"] = pd.to_datetime(trades["raw_date"], format="mixed", errors="coerce")
print(trades[["raw_date", "date"]])
print(trades.loc[trades["date"].isna(), "raw_date"].tolist())
        raw_date       date
0     2026-03-04 2026-03-04
1     03/04/2026 2026-03-04
2       20260304 2026-03-04
3  March 4, 2026 2026-03-04
4     not a date        NaT
['not a date']

How do I match a trade to a month?

A file of monthly data often keys each month by a number such as 202603, and .dt.strftime("%Y%m") writes each date’s year and month as text, which .astype("Int64") turns into that number. Int64, with a capital I, keeps the unreadable date as missing, where the ordinary int type would fail. .dt.to_period("M") gives the calendar month itself, which suits date arithmetic.

.dt gives a column of dates its date operations.

The following box builds both month keys.

trades["year_month"] = trades["date"].dt.strftime("%Y%m").astype("Int64")
trades["month"] = trades["date"].dt.to_period("M")
print(trades[["date", "year_month", "month"]])
        date  year_month    month
0 2026-03-04      202603  2026-03
1 2026-03-04      202603  2026-03
2 2026-03-04      202603  2026-03
3 2026-03-04      202603  2026-03
4        NaT        <NA>      NaT

The month number must have the same type in both files, so a number in one file and text in the other would merge nothing.

How do I assign trades to minutes and measure the gaps?

pd.to_timedelta(clock) reads a clock time as a duration since midnight, so the date plus the duration gives each trade’s timestamp. .dt.floor("min") returns the start of each trade’s minute, so the trades at 09:00:13 and 09:00:59.9 both fall in the 09:00 bar, and .diff() gives the time since the previous trade, which .dt.total_seconds() turns into seconds.

.dt.round("min") would move 09:00:59.9 to 09:01. The rows are in time order for one stock, and with several stocks the differences are taken within each stock.

The following box builds the timestamps, the minute bars and the gaps.

trades["timestamp"] = trades["date"] + pd.to_timedelta(trades["clock"])
trades["minute"] = trades["timestamp"].dt.floor("min")
trades["gap_seconds"] = trades["timestamp"].diff().dt.total_seconds()
print(trades[["timestamp", "minute", "gap_seconds"]])
                timestamp              minute  gap_seconds
0 2026-03-04 09:00:13.250 2026-03-04 09:00:00          NaN
1 2026-03-04 09:00:59.900 2026-03-04 09:00:00        46.65
2 2026-03-04 09:01:02.000 2026-03-04 09:01:00         2.10
3 2026-03-04 15:59:58.000 2026-03-04 15:59:00     25136.00
4                     NaT                 NaT          NaN

The fourth trade follows the third after 25,136 seconds, about seven hours.

Your turn

Count the trades in each one-minute bar. You should see 2 at 09:00 and 1 each at 09:01 and 15:59.

.value_counts() counts each bar and skips the missing one, and .sort_index() puts the bars in time order.

print(trades["minute"].dt.strftime("%H:%M").value_counts().sort_index().to_dict())
{'09:00': 2, '09:01': 1, '15:59': 1}