Python / Data Science Essentials Interview Questions
How do you work with dates and times in Pandas?
Time-series data is everywhere in data science — sales by day, sensor readings by second, user activity by hour. Pandas has first-class datetime support built on NumPy's datetime64 type and Python's datetime module.
import pandas as pd
df = pd.DataFrame({
'date_str': ['2024-01-15', '2024-02-20', '2024-03-05'],
'value': [100, 200, 150],
})
# Parse string dates — always specify format for speed and correctness
df['date'] = pd.to_datetime(df['date_str'], format='%Y-%m-%d')
# Extract components via .dt accessor
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', 'Tuesday', ...
df['quarter'] = df['date'].dt.quarter
# Date arithmetic
df['days_since'] = (pd.Timestamp.today() - df['date']).dt.days
df['next_month'] = df['date'] + pd.DateOffset(months=1)
# Set as index for time-series resampling
ts = df.set_index('date')
ts.resample('M').sum() # sum by month
ts.resample('W').mean() # mean by week
ts.resample('Q').agg({'value': ['sum', 'count']}) # quarterly stats
# Filtering date ranges
df[df['date'] >= '2024-02-01']
df[df['date'].between('2024-01-01', '2024-03-01')]Always parse dates explicitly with format= rather than relying on infer_datetime_format=True — the inferred path is slow and occasionally wrong for ambiguous formats like 01/02/03. For production pipelines, parse at read time using parse_dates=['date_col'] in pd.read_csv.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
