EnergyBoy
EnergyBoy

Reputation: 625

Python datetime.now() as a default function parameter return same value in different time

Now I got some problem that I can't explain and fix.
This is my first python module

TimeHelper.py

from datetime import datetime

def fun1(currentTime = datetime.now()):
    print(currentTime)

and another is

Main.py

from TimeHelper import fun1
import time

fun1()
time.sleep(5)
fun1()

When I run the Main.py, the out put is
2020-06-16 09:17:52.316714
2020-06-16 09:17:52.316714

My problem is why the time will be same in the result ? Is there any restrict when passing datetime.now() in to default parameter ?

Upvotes: 13

Views: 3805

Answers (3)

EnergyBoy
EnergyBoy

Reputation: 625

I think I find the answer. Thanks for @user2864740
So I change my TimeHelper.py to this

from datetime import datetime

def fun1(currentTime = None):
    if currentTime is None:
        currentTime = datetime.now()
    print(currentTime)

and anything work in my expectation.

Upvotes: 14

Sarthak Kumar
Sarthak Kumar

Reputation: 304

It's because when you define a function datetime.now() is evaluated only at that time and that value is stored in currentTime, So whenever you run fun1 currentTime value does not update.
you can Simply do this in TimeHelper.py

from datetime import datetime

def fun1(currentTime=None):
    if currentTime:
        print(currentTime)
    else:
        print(datetime.now())

Hope it helps :)

Upvotes: 5

Dawid Wawrzynczyk
Dawid Wawrzynczyk

Reputation: 173

When assigning the variable in the function you actually assign it only once when you import the function. To assign it dynamically you need to set the variable inside the function every time it is ran.

from datetime import datetime

def fun1():
    currentTime = datetime.now()
    print(currentTime)

Edit:

If you want to specifically say what time then:

from datetime import datetime

def fun1(time):
    currentTime = time
    print(currentTime)

Upvotes: 0

Related Questions