Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 1000
EnergyBoy Avatar asked Jun 16 '20 01:06

EnergyBoy


People also ask

What does datetime NOW () return in Python?

now() function Return the current local date and time, which is defined under datetime module. Parameters : tz : Specified time zone of which current time and date is required.

Does datetime now have timezone?

Python datetime now() function accepts timezone argument that should be an implementation of tzinfo abstract base class. Python pytz is one of the popular module that can be used to get the timezone implementations. You can install this module using the following PIP command.

Is datetime datetime NOW () UTC?

Getting the UTC timestampUse the datetime. datetime. now() to get the current date and time. Then use tzinfo class to convert our datetime to UTC.

What is the difference between time and datetime module in Python?

The time module is principally for working with Unix time stamps; expressed as a floating point number taken to be seconds since the Unix epoch. the datetime module can support many of the same operations, but provides a more object oriented set of types, and also has some limited support for time zones.


1 Answers

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.

like image 101
EnergyBoy Avatar answered Sep 27 '22 17:09

EnergyBoy