Parse dates and group time series
3.1.1
Turn dates into usable values, choose a time grain, and handle invalid or time-zone-aware rows.
On this page
Parse using a known format
Use to_datetime with a format when the source follows a fixed pattern. errors="coerce" converts invalid inputs to NaT. Use utc=True if converting offset-aware values to a common UTC timeline, and choose the reporting timezone before grouping by local day.
import pandas as pd
dates = pd.to_datetime(pd.Series(["2023-03-01", "ERROR"]), format="%Y-%m-%d", errors="coerce")
print(dates.isna().tolist())
Example output
[False, True]
Group by calendar month
Use a monthly period to label records by calendar month. Resampling on a datetime index creates regular time bins. Choose explicit aggregation and distinguish empty months from months with meaningful zero sales.
import pandas as pd
sales = pd.DataFrame({"date": pd.to_datetime(["2023-01-05", "2023-01-09", "2023-02-02"]), "total": [4, 2, 6]})
monthly = sales.groupby(sales["date"].dt.to_period("M"))["total"].sum(min_count=1)
print({str(month): float(value) for month, value in monthly.items()})
Example output
{'2023-01': 6.0, '2023-02': 6.0}