如何使用 python 和时间安排将日期和时间保存到 excel
how to save date and time to excel using python with time scheduling
我是 python 的新手,我想使用 python 每 5 秒将当前日期和时间保存到 excel,但它只会保存我添加的 1 [=13] =]查看调度程序是否正常工作,但它不会保存到 excel。只要脚本是 运行.
,我就希望它持续保存
This is what I get
This is what I want
import datetime
import schedule
import time
from openpyxl import Workbook
def my_function ():
now = datetime.datetime.now()
nowDate = now.strftime('%Y-%m-%d %H:%M:%S')
wb = Workbook()
sheet1 = wb.active
sheet1.title = 'sampleSheet'
sheet1.cell(row=1, column=1).value = nowDate
wb.save(filename='test.xlsx')
print(nowDate)
schedule.every(5).seconds.do(my_function)
while 1:
schedule.run_pending()
time.sleep(1)
只需在函数外部创建一个索引变量(row_no)以指向要插入新数据的当前行。
在函数外创建工作簿对象。在您的情况下,每次调用该函数并创建一个新的工作簿对象时。
我评论了编辑内容。
代码如下:-
import datetime
import schedule
import time
from openpyxl import Workbook
row_no = 1 # new code
wb = Workbook() # taken outside from my_function
def my_function ():
global row_no # new code
global wb # new code
now = datetime.datetime.now()
nowDate = now.strftime('%Y-%m-%d %H:%M:%S')
sheet1 = wb.active
sheet1.title = 'sampleSheet'
sheet1.cell(row=row_no, column=1).value = nowDate # row=row_no
row_no += 1 # new code
wb.save(filename='test.xlsx')
print(nowDate)
schedule.every(5).seconds.do(my_function)
while 1:
schedule.run_pending()
time.sleep(1)
我是 python 的新手,我想使用 python 每 5 秒将当前日期和时间保存到 excel,但它只会保存我添加的 1 [=13] =]查看调度程序是否正常工作,但它不会保存到 excel。只要脚本是 运行.
,我就希望它持续保存This is what I get
This is what I want
import datetime
import schedule
import time
from openpyxl import Workbook
def my_function ():
now = datetime.datetime.now()
nowDate = now.strftime('%Y-%m-%d %H:%M:%S')
wb = Workbook()
sheet1 = wb.active
sheet1.title = 'sampleSheet'
sheet1.cell(row=1, column=1).value = nowDate
wb.save(filename='test.xlsx')
print(nowDate)
schedule.every(5).seconds.do(my_function)
while 1:
schedule.run_pending()
time.sleep(1)
只需在函数外部创建一个索引变量(row_no)以指向要插入新数据的当前行。
在函数外创建工作簿对象。在您的情况下,每次调用该函数并创建一个新的工作簿对象时。
我评论了编辑内容。
代码如下:-
import datetime
import schedule
import time
from openpyxl import Workbook
row_no = 1 # new code
wb = Workbook() # taken outside from my_function
def my_function ():
global row_no # new code
global wb # new code
now = datetime.datetime.now()
nowDate = now.strftime('%Y-%m-%d %H:%M:%S')
sheet1 = wb.active
sheet1.title = 'sampleSheet'
sheet1.cell(row=row_no, column=1).value = nowDate # row=row_no
row_no += 1 # new code
wb.save(filename='test.xlsx')
print(nowDate)
schedule.every(5).seconds.do(my_function)
while 1:
schedule.run_pending()
time.sleep(1)