← 30 Days of Python
Day 16 / 30String & Date

String & Date Operations

Dates and strings are where most data quality issues hide. A date column stored as text, inconsistent date formats, mixed timezone data — you will see all of these in real analyst roles.

1
Easy

How do you work with string columns in Pandas using .str accessor?

Python Answer
df["city"].str.upper()                  # uppercase
df["city"].str.strip()                  # remove whitespace
df["city"].str.replace("Old", "New")    # replace
df["city"].str.contains("Delhi")        # True/False
df["city"].str.startswith("M")          # True/False
df["city"].str.len()                    # string length
df["city"].str.split(",").str[0]        # split and get first part
💡

The .str accessor applies Python string methods to an entire column at once — no loop needed. It is vectorised and handles NaN gracefully (returns NaN for null values).

2
Easy

How do you convert a column to datetime?

Python Answer
df["date"] = pd.to_datetime(df["date"])

# With explicit format (much faster):
df["date"] = pd.to_datetime(df["date"], format="%d/%m/%Y")

# Handle errors:
df["date"] = pd.to_datetime(df["date"], errors="coerce")  # bad dates → NaT
💡

Always specify format= when you know the date format — it is 5-10x faster than auto-detection. NaT (Not a Time) is the datetime equivalent of NaN.

3
Medium

How do you extract date parts from a datetime column?

Python Answer
df["date"] = pd.to_datetime(df["date"])

df["year"]    = df["date"].dt.year
df["month"]   = df["date"].dt.month
df["day"]     = df["date"].dt.day
df["weekday"] = df["date"].dt.day_name()   # "Monday"
df["quarter"] = df["date"].dt.quarter
df["week"]    = df["date"].dt.isocalendar().week
💡

The .dt accessor is for datetime columns — equivalent to .str for strings. Extracting year and month is the foundation of time-series groupby: df.groupby(df["date"].dt.month)["sales"].sum().

4
Medium

How do you calculate the difference between two dates?

Python Answer
df["hire_date"] = pd.to_datetime(df["hire_date"])
df["today"] = pd.Timestamp.today()

df["tenure_days"] = (df["today"] - df["hire_date"]).dt.days
df["tenure_years"] = df["tenure_days"] / 365.25

# Difference in months:
from dateutil.relativedelta import relativedelta
# (use apply for complex month differences)
💡

Date subtraction returns a Timedelta. Use .dt.days to get the numeric value. This pattern is used for calculating customer age, employee tenure, days since last purchase, etc.

5
Medium

How do you filter a DataFrame by date range?

Python Answer
df["date"] = pd.to_datetime(df["date"])

# Filter Q1 2026:
mask = (df["date"] >= "2026-01-01") & (df["date"] <= "2026-03-31")
df_q1 = df[mask]

# Using between:
df_q1 = df[df["date"].between("2026-01-01", "2026-03-31")]
💡

Pandas compares datetime columns with string dates automatically when the column is already datetime type. Always convert to datetime first — comparisons on string dates give wrong results.

EVIKA ACADEMY · PYTHON FOR DATA ANALYTICS

Want to master Python with live practice?

Join our Python for Data Analysis course — live classes in Noida and online across India.

Book Free Demo Class →
← PREVIOUSDay 15: Merging & Joining DataFramesNEXT →Day 17: Matplotlib — Charts & Plots
Best Data Analytics Course in Noida Delhi NCR | EVIKA ACADEMY