Date & Time Handling

Python · Data Cleaning

Theory

Once a column is datetime64 (via pd.to_datetime or parse_dates), the .dt accessor exposes its parts: .dt.year, .dt.month, .dt.day, .dt.day_name(), .dt.quarter, .dt.hour and .dt.date. .dt.to_period('M') turns dates into months like 2024-01 for monthly grouping, and .dt.strftime('%d-%b-%Y') formats them as text.

Date arithmetic works with Timedelta: df['order_date'] + pd.Timedelta(days=7) gives a due date, and subtracting two date columns gives a Timedelta whose .dt.days is the gap in days. pd.DateOffset(months=1) moves by calendar months. pd.date_range('2024-01-01', periods=7, freq='D') builds a date sequence. resample('ME', on='order_date')['amount'].sum() groups by calendar month end ('W' for weeks, 'D' for days) - like a groupby on a time bucket that also includes empty periods. Comparisons work directly: df[df['order_date'] >= '2024-02-01'].

Why we use it

Most business questions are about time - sales per month, delivery delay in days, orders this week. The .dt accessor and resample turn raw timestamps into these answers without manual string slicing.

When to use it

Convert date text to datetime first, then use .dt for parts, subtraction for durations and resample or to_period for time buckets. For grouping by month alongside other keys, groupby with dt.to_period('M') is often simpler than resample.

How it works

  1. Date column as text
  2. Convert with pd.to_datetime(...)
  3. Need parts of the date? Yes: Use .dt.year / .month / .day_name(). No: Go on.
  4. Need durations or due dates? Yes: Subtract dates or add pd.Timedelta. No: Go on.
  5. Bucket by period: dt.to_period('M') or resample('ME')
  6. Time-based columns and summaries

Syntax

s.dt.year / .month / .day_name() / .quarter
s.dt.to_period('M')
s + pd.Timedelta(days=n); (end - start).dt.days
df.resample('ME', on='date_col')['x'].sum()

Example

df['month'] = df['order_date'].dt.to_period('M')
df['days'] = (df['delivered'] - df['order_date']).dt.days

Key points

Python topics

Getting Started

Variables & Data Types

Operators

Strings

Lists

Tuples

Sets

Dictionaries

Control Flow

Loops

Functions & OOP

Working with Data

Tooling & Errors

File Handling

Exception Handling

NumPy Library

Pandas Basics

Data Cleaning

Combining DataFrames (SQL Joins & Unions)

GroupBy & SQL-Style Analytics

Reshaping & Workflow

Data Visualization

Machine Learning (Scikit-Learn)

Advanced Python & AI

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Python for Data Analysts

From basics to business insights — the complete step-by-step Python roadmap. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice Python Online 141 Python questions for data analysts — strings, records, dates, statistics and regex — with hidden tests and instant verdicts. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Python  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
▶ Try It Live — runs real Python 3.12 in your browser (first run loads the engine)
{{ liveOutput }}
{{ liveError }}
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic