When I call on datetime.now() in my program it calls the current time, but when I call it again, it displays the previous time. How can I update datetime.now() so it calls the current time eachtime?
You say:
but when I call it again
... but you're NOT calling it again. You're more-than-likely printing/outputting the value of the variable that the first datetime.now() was assigned to.
Let's say you have the following:
from datetime import datetime
first_time = str(datetime.now())
print('First datetime.now() value: %s' % first_time)
You're probably attempting to get the updated time by simply printing first_time
(what you incorrectly refer to as "calling" ).
Instead, you should either overwrite first_time
by reassigning datetime.now() to it, or you should declare a new variable and assign datetime.now() to it.
# Overwriting & outputting:
# first_time = datetime.now()
# Declaring a new (updated) value (what I'll use in the example):
second_time = datetime.now()
# Outputting:
print('first_time: %s\nsecond_time: %s' % (str(first_time), str(second_time)))
You can define as follows:
def now():
return datetime.datetime.now().strftime('%d.%m.%Y %H:%M:%S')
use the definition in the following way:
print('{}'.format(now()))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.