Replacing Parts of a Datetime in Python – Complete Guide for Data Science 2026
Replacing specific parts of a datetime object (year, month, day, hour, minute, etc.) is a common and powerful operation in data science. It allows you to normalize timestamps, set all records to the start of the day, align events to specific times, or adjust timezones without recreating the entire object. The .replace() method makes this task clean, readable, and efficient.
TL;DR — How to Replace Datetime Parts
dt.replace(year=..., month=..., hour=..., etc.)- Works on both
datetimeanddateobjects - Creates a new object (immutable-style behavior)
- Pandas equivalent with
.dtaccessor orpd.to_datetime
1. Basic .replace() Usage
from datetime import datetime
from zoneinfo import ZoneInfo
dt = datetime(2026, 3, 19, 14, 30, 0, tzinfo=ZoneInfo("UTC"))
# Replace specific parts
dt_midnight = dt.replace(hour=0, minute=0, second=0, microsecond=0)
dt_new_year = dt.replace(year=2027)
dt_new_month = dt.replace(month=12)
print(dt_midnight) # 2026-03-19 00:00:00+00:00
2. Real-World Data Science Examples
import pandas as pd
df = pd.read_csv("sales_data.csv", parse_dates=["order_date"])
# Example 1: Normalize all timestamps to midnight (start of day)
df["order_date_start"] = df["order_date"].apply(
lambda x: x.replace(hour=0, minute=0, second=0, microsecond=0)
)
# Example 2: Set all events to the same hour for comparison
df["order_date_hour"] = df["order_date"].apply(lambda x: x.replace(minute=0, second=0))
# Example 3: Move all records to the first day of the month
df["first_of_month"] = df["order_date"].apply(lambda x: x.replace(day=1))
3. Replacing Timezone Information
dt = datetime.now(ZoneInfo("UTC"))
# Change timezone without changing the instant in time
dt_ny = dt.replace(tzinfo=ZoneInfo("America/New_York")) # wrong way
# Correct way:
dt_ny = dt.astimezone(ZoneInfo("America/New_York"))
4. Best Practices in 2026
- Use
.replace()for simple component changes on individual datetime objects - For large DataFrames, prefer vectorized pandas methods or
.apply()with lambda - Always work with timezone-aware objects before replacing parts
- Keep original datetime column and create new derived columns for replaced values
- Use
replace()to normalize times (e.g., set to midnight or hour start)
Conclusion
Replacing parts of a datetime object with .replace() is a simple yet powerful technique that every data scientist should master. In 2026, it is commonly used for normalizing timestamps, creating start-of-day/hour features, aligning data, and preparing clean time-based features for modeling and reporting.
Next steps:
- Go through one of your datasets and create new columns by replacing specific parts of the datetime (e.g., start of day, first of month, etc.)