Ad
How To Save Date And Time To Excel Using Python With Time Scheduling
I'm new to python and I want to save the current date and time to excel every 5 seconds using python but it only saves 1 I added print(nowDate)
to see if the scheduler is working and it is but it wont save to excel. I want it to save continuously as long the script is running.
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)
Ad
Answer
Just create a index variable (row_no) outside the function to point to the current row where the new data is going to be inserted.
Create the workbook object outside the function. In your case, every time the function is getting called and a new workbook object is getting created.
I've commented the edits.
Here's the code:-
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)
Ad
source: stackoverflow.com
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module
Ad