[英]Python - How to update datetime.now()
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.当我在我的程序中调用 datetime.now() 时,它会调用当前时间,但是当我再次调用它时,它会显示上一次。 How can I update datetime.now() so it calls the current time eachtime?如何更新 datetime.now() 以便每次调用当前时间?
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.您很有可能打印/输出第一个datetime.now() 分配给的变量的值。
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" ).您可能试图通过简单地打印first_time
(您错误地称为"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.相反,您应该通过将datetime.now()重新分配给它来覆盖first_time
,或者您应该声明一个新变量并将datetime.now()分配给它。
# 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()))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.