from datetime import datetime

# Get current date and time
now = datetime.now()
print(now)  # 2026-01-25 14:30:45.123456

# Create a specific datetime object
specific_date = datetime(2026, 1, 25, 14, 30, 45)
print(specific_date)  # 2026-01-25 14:30:45

Python’s datetime module handles date and time operations through five core classes. The datetime.datetime class represents a specific point in time with year, month, day, hour, minute, second, and microsecond precision.

The date class stores calendar dates without time information. The time class holds time values independent of dates. The timedelta class measures durations between two points in time. The tzinfo class provides timezone information for aware datetime objects.

Creating Python datetime objects

The datetime constructor accepts integer arguments in descending order of significance. Year, month, and day are required parameters. Hour, minute, second, and microsecond default to zero when omitted.

from datetime import datetime, date, time

# Full datetime with all components
dt = datetime(2026, 1, 25, 14, 30, 45, 500000)
print(dt)  # 2026-01-25 14:30:45.500000

# Date only
d = date(2026, 1, 25)
print(d)  # 2026-01-25

# Time only
t = time(14, 30, 45)
print(t)  # 14:30:45

The now() method retrieves the current local datetime. The today() method returns the current date. The utcnow() method provides the current UTC datetime without timezone information.

from datetime import datetime, date

current_datetime = datetime.now()
current_date = date.today()
utc_time = datetime.utcnow()

print(f"Local: {current_datetime}")
print(f"Date: {current_date}")
print(f"UTC: {utc_time}")

Extracting Python datetime components

Datetime objects expose individual components as attributes. Access year, month, day, hour, minute, second, and microsecond directly from any datetime instance.

from datetime import datetime

dt = datetime(2026, 1, 25, 14, 30, 45)

print(dt.year)        # 2026
print(dt.month)       # 1
print(dt.day)         # 25
print(dt.hour)        # 14
print(dt.minute)      # 30
print(dt.second)      # 45
print(dt.weekday())   # 6 (Sunday)

The weekday() method returns integers from 0 (Monday) to 6 (Sunday). The isoweekday() method uses 1 (Monday) through 7 (Sunday) instead.

Formatting Python datetime with strftime()

The strftime() method converts datetime objects into formatted strings. Format codes specify how to represent each component. Common codes include %Y for four-digit year, %m for zero-padded month, %d for zero-padded day, %H for 24-hour format hour, and %M for minute.

from datetime import datetime

dt = datetime(2026, 1, 25, 14, 30, 45)

# Different format patterns
print(dt.strftime("%Y-%m-%d"))              # 2026-01-25
print(dt.strftime("%B %d, %Y"))             # January 25, 2026
print(dt.strftime("%m/%d/%Y %H:%M:%S"))     # 01/25/2026 14:30:45
print(dt.strftime("%I:%M %p"))              # 02:30 PM
print(dt.strftime("%A, %B %d, %Y"))         # Sunday, January 25, 2026

Use %A for full weekday name, %B for full month name, %I for 12-hour format, and %p for AM/PM designation.

Parsing strings with strptime()

The strptime() method converts string representations into datetime objects. The format string must match the input string’s structure exactly.

from datetime import datetime

date_string = "2026-01-25 14:30:45"
dt = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(dt)  # 2026-01-25 14:30:45

# Parsing different formats
date1 = datetime.strptime("January 25, 2026", "%B %d, %Y")
date2 = datetime.strptime("25/01/2026", "%d/%m/%Y")
date3 = datetime.strptime("2026-W04-7", "%Y-W%W-%w")

print(date1)  # 2026-01-25 00:00:00
print(date2)  # 2026-01-25 00:00:00
print(date3)  # 2026-01-25 00:00:00

Working with timedelta

Timedelta objects represent the difference between two datetime values. You can add or subtract timedelta from datetime objects to perform date arithmetic.

from datetime import datetime, timedelta

dt = datetime(2026, 1, 25, 14, 30)

# Add time
future = dt + timedelta(days=7, hours=3, minutes=15)
print(future)  # 2026-02-01 17:45:00

# Subtract time
past = dt - timedelta(weeks=2, days=3)
print(past)  # 2026-01-04 14:30:00

# Calculate difference between dates
date1 = datetime(2026, 1, 25)
date2 = datetime(2026, 2, 15)
difference = date2 - date1
print(difference.days)  # 21
print(difference.total_seconds())  # 1814400.0

Timedelta accepts days, seconds, microseconds, milliseconds, minutes, hours, and weeks as arguments. Internal storage uses only days, seconds, and microseconds for precision.

Timezone handling with Python datetime

The datetime module provides basic timezone support through the timezone class. For production applications, use the zoneinfo module (Python 3.9+) or pytz library for comprehensive timezone handling.

from datetime import datetime, timezone, timedelta

# Create timezone-aware datetime
utc = timezone.utc
dt_utc = datetime(2026, 1, 25, 14, 30, tzinfo=utc)
print(dt_utc)  # 2026-01-25 14:30:00+00:00

# Custom timezone offset
est = timezone(timedelta(hours=-5))
dt_est = datetime(2026, 1, 25, 9, 30, tzinfo=est)
print(dt_est)  # 2026-01-25 09:30:00-05:00

# Convert between timezones
dt_converted = dt_utc.astimezone(est)
print(dt_converted)  # 2026-01-25 09:30:00-05:00

Using pytz for more complex timezone operations:

from datetime import datetime
import pytz

# Define timezones
ny_tz = pytz.timezone('America/New_York')
tokyo_tz = pytz.timezone('Asia/Tokyo')

# Create timezone-aware datetime
ny_time = ny_tz.localize(datetime(2026, 1, 25, 9, 30))
print(ny_time)  # 2026-01-25 09:30:00-05:00

# Convert to Tokyo time
tokyo_time = ny_time.astimezone(tokyo_tz)
print(tokyo_time)  # 2026-01-25 23:30:00+09:00

Integrating Python datetime with pandas groupby

Pandas extends datetime functionality for data analysis through the dt accessor. This accessor provides methods to extract datetime components and enables grouping operations on time-based data.

import pandas as pd
from datetime import datetime, timedelta

# Create sample dataframe with datetime
dates = pd.date_range(start='2026-01-01', periods=100, freq='D')
df = pd.DataFrame({
    'date': dates,
    'sales': range(100, 200),
    'region': ['North', 'South', 'East', 'West'] * 25
})

# Extract datetime components
df['year'] = df['date'].dt.year
df['month'] = df['date'].dt.month
df['day_of_week'] = df['date'].dt.dayofweek
df['week'] = df['date'].dt.isocalendar().week

print(df.head())

The pandas groupby operation combined with datetime enables powerful time-based aggregations. Group data by any datetime component using the dt accessor.

# Group by month and calculate total sales
monthly_sales = df.groupby(df['date'].dt.month)['sales'].sum()
print(monthly_sales)

# Group by day of week
weekday_sales = df.groupby(df['date'].dt.dayofweek)['sales'].mean()
print(weekday_sales)

# Multiple grouping with datetime and other columns
region_month = df.groupby([df['date'].dt.month, 'region'])['sales'].sum()
print(region_month)

The pd.Grouper class provides more control over datetime grouping operations. Use the freq parameter to specify grouping frequency like daily (D), weekly (W), monthly (M), or yearly (Y).

# Group by week using pd.Grouper
weekly_sales = df.groupby(pd.Grouper(key='date', freq='W'))['sales'].sum()
print(weekly_sales)

# Group by month with custom aggregations
monthly_stats = df.groupby(pd.Grouper(key='date', freq='M')).agg({
    'sales': ['sum', 'mean', 'max', 'min']
})
print(monthly_stats)

# Combine pd.Grouper with other grouping columns
region_weekly = df.groupby([
    pd.Grouper(key='date', freq='W'),
    'region'
])['sales'].sum()
print(region_weekly)

Resample provides another approach for time-based grouping. This method works specifically with DatetimeIndex objects and offers identical functionality to pd.Grouper with cleaner syntax.

# Set datetime as index for resampling
df_indexed = df.set_index('date')

# Resample to weekly frequency
weekly_resample = df_indexed.resample('W')['sales'].sum()
print(weekly_resample)

# Resample to monthly with multiple aggregations
monthly_resample = df_indexed.resample('M').agg({
    'sales': ['sum', 'mean'],
    'region': 'first'
})
print(monthly_resample)

For more complex time series analysis, combine datetime operations with rolling windows and pandas groupby.

# Calculate 7-day rolling average by region
df_indexed['rolling_avg'] = (
    df_indexed.groupby('region')['sales']
    .transform(lambda x: x.rolling(window=7, min_periods=1).mean())
)

# Group by month and calculate statistics on rolling values
monthly_rolling = df_indexed.groupby(df_indexed.index.month).agg({
    'sales': 'sum',
    'rolling_avg': 'mean'
})
print(monthly_rolling)

The datetime module handles date arithmetic, formatting, and parsing operations. Pandas extends these capabilities for data analysis through the dt accessor and groupby operations. Together, they provide comprehensive tools for time-based data manipulation and aggregation. Use datetime for individual date operations and pandas groupby for analyzing time series datasets at scale.

Share.
Leave A Reply