Python para Data Science e Analytics
Python para Data Science e Analytics › Guides › How to handle dates in pandas: conversion, period extraction

How to handle dates in pandas: conversion, period extraction and resampling

To handle dates in pandas, the sequence is always the same: convert the column with pd.to_datetime, pull period components through the .dt accessor, and group the time series with resample when the analysis is by day, week or month. Once the column is a real datetime, sorting, range filters and aggregations run in chronological order instead of the alphabetical order of text. The examples below follow that order, which is also the order you usually need them in.

Topics: pandas, datas, datetime

How do you convert a text column to datetime in pandas?

When a file is read with pd.read_csv, date columns usually arrive as text with dtype object. In that format '31/01/2024' sorts before '02/02/2024', because the comparison runs character by character: the '3' comes before the '0'. Converting to datetime fixes the ordering, lets you subtract two dates to get elapsed days, and unlocks every period property used later.

The function at the centre of this is pd.to_datetime. When the column is day-first, pass format='%d/%m/%Y': this removes the ambiguity between day and month and stops pandas from reading 03/04 as either 3 April or 4 March. If the column carries dirty values, errors='coerce' turns anything unparseable into NaT instead of aborting the run, and you can then count the invalid rows before deciding what to do with them.

How do you extract day, month, week and quarter from a date?

Once the column is datetime, the .dt accessor exposes year, month, day, quarter and dayofweek. Two details catch most people: dayofweek starts at 0 for Monday, and the week of the year comes from .dt.isocalendar().week, which returns a Series with an unsigned integer dtype rather than a plain number you can feed straight into a merge. day_name() follows the locale configured in your environment, so the names come back in whatever language that locale defines.

For grouping by blocks of time, to_period is safer than extracting a bare number. to_period('M') keeps year and month together, so January 2023 and January 2024 land in different groups. Extracting only .dt.month puts both in the same bucket, which is a common source of wrong time series on any dataset longer than twelve months.

How do you analyze data by day, week or month with resample?

resample works on the index: the date column has to become the index with set_index and has to be a DatetimeIndex. The result is an intermediate object, not a finished table — you chain an aggregation such as .sum(), .mean() or .agg({...}) to define what happens to each column inside each bin.

The alias sets the bin size: 'D' for day, 'W' for week, 'MS' for the start of the month and 'ME' for the end of the month. On data with monetary values, the usual move is to sum the amount column and count the orders in the same call, using a dictionary inside .agg. Periods with no records come back as NaN, and that is information: it means no activity on that day, not that the data was lost.

When the date is not the index, or when you want the period combined with another category, groupby with pd.Grouper(freq=...) reaches the same result. The practical difference is that Grouper can group by period and by another column at the same time, which is what you need to compare months across stores or regions.

What common errors appear when working with dates in pandas?

The most frequent one is comparing text with a date. Filtering df[df['date'] > '2024-01-01'] on an object column does not raise an error — it returns something that looks plausible and is wrong, because the comparison is string based. Convert first, then filter.

The second is forgetting the index. Calling resample on a column that is still object raises TypeError, since the method needs a DatetimeIndex; run set_index('date') before it. The third is mixing two temporal granularities in the same group, as with month numbers that carry no year. The fourth is ignoring the alias change: on pandas 2.2, 'M' still runs but prints a FutureWarning pointing to 'ME' on every aggregation.

It also pays to check duplicated timestamps and NaT rows before resampling. resample does not repair gaps in the source data, it only bins what exists, so an empty day and a missing row end up looking the same unless you check isna() first.

How do you practice date handling before using it in a real project?

Date handling looks small until it breaks a dashboard. The reliable way to learn it is to run the three steps on a file you actually care about — convert, extract, resample — and then repeat them on a second file with a different date format, because format variation is where the errors live.

The Python for Data Science and Analytics course at python.paanalytics.net covers pandas alongside NumPy, data cleaning and preparation and outlier detection, which is exactly where date conversion shows up in practice: a text column read from a CSV, a monthly aggregation that has to be correct, a chart that must be in chronological order. The course runs from the basics — IDE and Jupyter Notebook setup, functions, loops and conditionals — through visualization and machine learning, and closes with an end-to-end exploratory analysis and machine learning project.

The format suits a topic like this one. Lessons are recorded and watched at your own pace, there are guided exercises, and the final project goes into a portfolio. Access does not expire, so you can return to the pandas lessons when a real dataset throws an unfamiliar date format at you. The price is R$ 470, or 12 installments of R$ 20.37 on a card, paid through the Hotmart checkout, which also accepts boleto. No prior programming is required to start, and completion comes with a certificate and an exclusive community for networking.

AliasPeriod coveredTypical use
DOne calendar dayDaily totals and daily averages
WOne week, ending on Sunday by defaultWeekly revenue and weekly order counts
MSStart of the monthMonthly averages anchored to the 1st
MEEnd of the monthMonthly closing totals
QEEnd of the quarterQuarterly comparisons
YEEnd of the yearAnnual summaries

Aliases as listed in the pandas offset alias documentation. pandas 2.2 renamed 'M', 'Q' and 'Y' to 'ME', 'QE' and 'YE' and keeps the older ones as deprecated.

Learn pandas from zero to the final project

Secure payment via Hotmart, up to 12 installments.

Enroll now Product site

Frequently asked questions

Do I need to convert a date column before sorting or filtering it?

Yes, if you want chronological order. On an object column, sorting compares strings, so '31/01/2024' comes before '02/02/2024'. After pd.to_datetime, sorting and range filters follow the calendar, and subtracting two dates gives elapsed days.

What is the difference between resample and groupby with Grouper?

resample requires a DatetimeIndex, so the date has to be the index. pd.Grouper(freq=...) works when the date is a regular column and also allows grouping by period and by another column in the same call, which resample alone does not do.

Why do some periods come back as NaN after resample?

Because there was no row in that bin. resample builds the full range between the first and last timestamp, so empty days show up as NaN. Use .fillna(0) if the analysis needs an explicit zero, but make that a deliberate choice.

How do I handle mixed or dirty date formats in one column?

On pandas 2.0 and later, format='mixed' parses row by row. Use dayfirst=True when the day leads, and errors='coerce' when the column is dirty, so unparseable values become NaT and can be counted with isna() before you drop or fix them.

Does the course cover pandas date handling?

pandas is part of the course content, alongside NumPy and the data cleaning and preparation block, with guided exercises and an end-to-end final project. Access does not expire, so the lessons stay available when you need to revisit them.

Ler em português →