当代码在循环上运行时,Python当前时间不变

2024-06-02 08:30:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python脚本,每5秒运行一个函数。我注意到当代码循环时,时间输出不会改变。只有当我停止代码并再次运行它时,它才会更改。但是我代码中的所有其他数据每5秒更新一次。我不知道日期的情况如何,因为我还没有测试过。因此,当再次调用该函数时,它会显示它第一次执行的时间。谢谢你抽出时间

代码

from datetime import datetime
from datetime import date
import time

today = date.today()
now = datetime.now()

def loaddata():

 date1 = today.strftime("%d/%m/%Y")
 print("d1 =", date1)
  
 current_time = now.strftime("%H:%M:%S")
 print("Current Time =", current_time)



schedule.every(5).seconds.do(loaddata)

while 1:
  schedule.run_pending()
  time.sleep(1)


Tags: 函数代码fromimporttodaydatetimedatetime
1条回答
网友
1楼 · 发布于 2024-06-02 08:30:47

您必须在fuction中声明todaynow

from datetime import datetime
from datetime import date
import time


def loaddata():

 today = date.today()
 now = datetime.now()
 date1 = today.strftime("%d/%m/%Y")
 print("d1 =", date1)
  
 current_time = now.strftime("%H:%M:%S")
 print("Current Time =", current_time)



schedule.every(5).seconds.do(loaddata)

while 1:
  schedule.run_pending()
  time.sleep(1)

相关问题 更多 >