Python datetime module can't change variable parameter

Viewed 113

I am a beginner. I tried running this on Jupyter Notebook.

x = 5
y = dt.date.today() + dt.timedelta(days = x)
print(y)
x = 1000
print(y)

and the result was

2020-08-01
2020-08-01

I don't understand why if x changes from 5 to 1000 days, y won't change either. Does the timedelta save the 5 input? Am I missing something with these parameters?

3 Answers

If I get the question right, you perceive y to behave like a function. Which is not the case in your code; it's a variable. As a contrasting example, if you assign a function to y instead, you get

import datetime as dt

def y(x):
    return dt.date.today() + dt.timedelta(days=x)

# equivalent lambda expression:
# y = lambda x: dt.date.today() + dt.timedelta(days=x)

x = 5
print(y(x))
# 2020-08-01

x = 1000
print(y(x))
# 2023-04-23

Note that now, there is only one assignment to y (which gets a little more clear if you look at the lambda expression). However, in each print statement, the function y is called (noticeable by the parentheses () after the function's name) with the variable x as input.

It's because you print y value. Asigning 1000 to x does not change anything unless you will add is (as timedelta) to y.

So your y is 2020-08-01 - it's defined here:

y = dt.date.today() + dt.timedelta(days = x)

This takes the value of x in the time when y is assigned (x = 5).

Changing x in following lines affects only x, it does not force everything to recalculate (y does not recalculate, till you write code for that).

Related