简体   繁体   English

在一分钟内运行 python function 但精确到新分钟的 00 秒

[英]Run python function in one minute but exact on 00 seconds of new minute

I want to run the code exact at 1 min timeframe but only when second will be zero.我想在 1 分钟的时间范围内准确运行代码,但仅当秒为零时才运行。

import yfinance as yf
company_name = '^NSEI'

# need to loop this code
df = yf.Ticker(company_name).history(period='1d', interval='1m')
print(df.tail(1))

If I run it multiple times, I am getting output as,如果我多次运行它,我会得到 output 作为,

2022-03-04 09:49:00+05:30  16283.849609  16283.849609  16269.049805  16279.150391       0          0             0
2022-03-04 09:50:00+05:30  16277.700195  16278.650391  16268.150391  16268.150391       0          0             0
2022-03-04 09:51:00+05:30  16269.200195  16274.799805  16262.950195  16274.549805       0          0             0
2022-03-04 09:52:00+05:30  16274.299805  16274.299805  16263.400391  16263.799805       0          0             0
2022-03-04 09:53:23+05:30  16263.250000  16263.250000  16263.250000  16263.250000       0          0             0

You can see last row, and its printed at "09:53:23+05:30" How can I run this code after exact 1 min timeframe?您可以看到最后一行,它打印在“09:53:23+05:30” 我怎样才能在准确的 1 分钟时间段后运行此代码? If I use time.sleep(60) then it may sleep for 60 seconds but I will not get output exact at "00" seconds.如果我使用 time.sleep(60) 那么它可能会休眠 60 秒,但我不会在“00”秒时准确得到 output。

I want to loop this so that it print rows perfectly after 1 min and thus rows should be printed as 09:52:00+05:30, 09:53:00+05:30, 09:54:00+05:30, etc我想循环它,以便它在 1 分钟后完美打印行,因此行应打印为 09:52:00+05:30、09:53:00+05:30、09:54:00+05:30 , ETC

If you want the code to wait for an exact minute and run the code when the second becomes 0, you can increase the precision for which the code is sleeping (for eg wait 100th of a second)如果您希望代码等待一分钟并在秒变为 0 时运行代码,您可以提高代码休眠的精度(例如等待 100 秒)

import datetime as dt
import time

while True:
    while dt.datetime.now().second:
        time.sleep(0.01)
    print(dt.datetime.now()) # Your yfinance code here

But if you just want the output to show 00 as seconds, then you can round it down as pointed out by @k33da_the_bug in the comments.但是,如果您只想将 output 显示为秒数 00,则可以按照@k33da_the_bug在评论中指出的那样将其四舍五入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM