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.
More Related questions...