Date.replace statment to print year-1

Hello and thanks for nay help.

I’m currently running through some training and a complete Python starter. my training says to use this statement to out put a given date with 1 year minus.

Howevver this is not working and erroring would anybody know the correct syntax for this please?

date2 = date.replace (year=date.year-1)
print (date2)

Please share all the code you are running and all the error messages you see. For me this works:

% py
Python 3.13.2 (v3.13.2:4f8bb3947cf, Feb  4 2025, 11:51:10) [Clang 15.0.0 (clang-1500.3.9.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
:>>> import datetime
:>>> d = datetime.datetime.now()
:>>> d
datetime.datetime(2025, 10, 10, 9, 39, 16, 715571)
:>>> d.replace(year=2024)
datetime.datetime(2024, 10, 10, 9, 39, 16, 715571)
:>>> d.replace(year=d.year-1)
datetime.datetime(2024, 10, 10, 9, 39, 16, 715571)
:>>> d2 = d.replace(year=d.year-1)
:>>> d2
datetime.datetime(2024, 10, 10, 9, 39, 16, 715571)
:>>>
1 Like

Hello Barry, thanks for the help.

the code:

# Write and test the function
from pandas import DataFrame
import datetime

def create_yield_table(data: DataFrame, date: datetime) -> DataFrame:
    """
    Function to build a yield table object

    Parameters
    ----------
    data : DataFrame
        Yield curve data to be used
    date : datetime
        The date to use for the current date

    Yields
    -------
    DataFrame
        A yield table

    """

# Find the other 2 dates
date2 = d.replace(year=date.year-1)
date3 = d.replace(year=date.year-5)
print (date2)

# Index into the three dates and copy
table = yield_curve.loc[[date, date2, date3]].copy()

# Transpose
table = table.T
print(table)

# Rename the Columns
table.columns = ["Current", "1 Year Ago Curve", "5 Years Ago Curve"]

# Get the changes in the yield curve
table["1 years Change"] = table["Current"] - table["1 Year Ago Curve"]
table["5 year Change"] = table["Current"] - table["5 Years Ago Curve"]

#return table
yield_table = create_yield_table(yield_curve, datetime(2019,12,31))
print(yield_table)

the error:

Traceback (most recent call last):
File “C:\Users\ext.jleslie1\PyCharmMiscProject\section 2 lec3.py”, line 115, in
date2 = d.replace(year=date.year-1)
^
NameError: name ‘d’ is not defined. Did you mean: ‘pd’?

Process finished with exit code 1

Error message says quite specifically what the problem is: there is no d defined.

There is function parameter defined as date so maybe it must be date2 = date.replace(year=date.year-1)