The python program with datetime mofule - python-3.x

I write this code in python in order to read the minute of windows clock and recognize weather it is even or odd and do it 10 times with random sleep time between 5 to 10 seconds:
from datetime import datetime
import random
import time
wait_time = random.randint(5,11)
time.sleep(wait_time)
for i in range(10):
even=[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,
34,36,38,40,42,44,46,48,50,52,54,56,58]
m=datetime.today().minute
if m in even:
print("It is even")
else:
print("It is odd")
But when I run it, sleep time works ok but it show the answer just one time. I think I should write the lines in other arrangement. But I don't know how to fix it.

You need to rearrange your lines according to your own description as below. Same lines but another ordering.
from datetime import datetime
import random
import time
even=[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,
34,36,38,40,42,44,46,48,50,52,54,56,58]
for i in range(10):
m=datetime.today().minute
if m in even:
print("It is even")
else:
print("It is odd")
wait_time = random.randint(5,11)
time.sleep(wait_time)

Related

Passing run_date in seconds to apscheduler's add_job

I want to schedule a function in APScheduler to happen only once in the specified time from now. The run_date date trigger accepts datetime objects and/or strings there of:
from datetime import datetime
import os
from apscheduler.schedulers.asyncio import AsyncIOScheduler
try:
import asyncio
except ImportError:
import trollius as asyncio
def tick():
print('Tick! The time is: %s' % datetime.now())
if __name__ == '__main__':
scheduler = AsyncIOScheduler()
scheduler.add_job(tick, 'date', run_date=datetime.fromordinal(datetime.toordinal(datetime.now())+1))
scheduler.start()
print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))
# Execution will block here until Ctrl+C (Ctrl+Break on Windows) is pressed.
try:
asyncio.get_event_loop().run_forever()
except (KeyboardInterrupt, SystemExit):
pass
Is there a built-in functionality in APScheduler to specify the delay time directly in seconds, e.g.something like application_start_time + specified_delay? I tried datetime.fromordinal(datetime.toordinal(datetime.now())+1) as argument to run_date for 1 second after the starting point of my application, but this only hangs for ever without calling the tick function showing the following deprecation message:
Press Ctrl+C to exit
/tmp/a.py:30: DeprecationWarning: There is no current event loop
asyncio.get_event_loop().run_forever()
What you probably wanted was:
from datetime import datetime, timedelta, timezone
scheduler.add_job(tick, "date", run_date=datetime.now(timezone.utc) + timedelta(seconds=1))

Stock price logging function

I have this function where the price of a stock gets logged in real time every 2 seconds and save it into a csv file however I cant see anything in the csv when I open it. What am I missing from the script?
import pandas as pd
import time
import urllib
import sys
import fix_yahoo_finance as yf
def stocks():
# Enter stock symbol
stock = input("Enter stock: ")
# Name CSV file
csvy= str(stock) + time.strftime('.%A.%d.%b.%Y').replace(' ', '') + ".csv"
csvy = csvy.replace(':' , '')
with open(csvy, 'w') as f:
sys.stdout = f
while 1 > 0:
print(yf.get_live_price(stock))
time.sleep(2)
stocks()
You wrote:
print(yf.get_live_price(stock))
You want to additionally flush the buffer so your new text is immediately visible:
print(yf.get_live_price(stock), flush=True)
Alternatively, consider assigning the live price to a temp variable,
and then outputting it twice, with print() and f.write(),
rather than assigning a new value to stdout.
Then you'd be able to flush them independently according to your need,
f.flush() or sys.stdout.flush().

Capture a terminal output in real time of an python module

The python 'yfinance' module downloads the quotes of many Financial Securities in a pandas dataframe and in the meanwhile it displays a progress bar in the console. In this way:
import yfinance as yf
Tickerlist = ["AAPL","GOOG","MSFT"]
quote = yf.download(tickers=Tickerlist,period='max',interval='1d',group_by='ticker')
I would like to capture the console progress bar in real time, and the code should be this:
import sys
import subprocesss
process = subprocess.Popen(["yf.download","tickers=Tickerlist","period='max'","interval='1d'","group_by='ticker'"],stdout=quote)
while True:
out = process.stdout.read(1)
sys.stdout.write(out)
sys.stdout.flush()
I make a big mess with subprocess. I need your help! Thanks.
I have already seen all the links that deal with this topic but without being able to solve my problem.
You need two python files to do what you want.
one is yf_download.py and second is run.py
The file code looks like this and you can run it through run.py
python run.py
yf_download.py
import sys
import yfinance as yf
Tickerlist = ["AAPL","GOOG","MSFT"]
def run(period):
yf.download(tickers=Tickerlist, period=period,interval='1d',group_by='ticker')
if __name__ == '__main__':
period = sys.argv[1]
run(period)
run.py
import sys
import subprocess
process = subprocess.Popen(["python", "yf_download.py", "max"],stdout=subprocess.PIPE)
while True:
out = process.stdout.read(1)
if process.poll() is not None:
break
if out != '':
sys.stdout.buffer.write(out)
sys.stdout.flush()

Python import pygame does not play an audio

the code just print the name of the song and dont stop after he finish
my code:
import glob
import os
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
import pygame
songs = glob.glob("C:\\Users\zivsi\Music\\*.mp3")
import random
song = random.choice(songs)
song_name = song.replace("C:\\Users\zivsi\Music\\", "").replace(".mp3", "")
print("song: ", song_name)
pygame.init()
pygame.mixer.music.load(song)
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(10)
I did not use from pygame import *
because it cannot be done in def
Use pygame.mixer.music.stop() when you want to stop the music. The pygame.time.Clock().tick(10) computes the time since it was last called and stalls the program until 1/framerate (in your case framerate=10) seconds have passed. Therefore, your code will run until the song is done playing. If instead you want to pause the program for a set amount of time and stop the music from playing, use time.sleep(), which takes seconds as an argument. Possible example:
import glob
import os
import time
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
import pygame
songs = glob.glob("C:\\Users\zivsi\Music\\*.mp3")
import random
song = random.choice(songs)
song_name = song.replace("C:\\Users\zivsi\Music\\", "").replace(".mp3", "")
print("song: ", song_name)
pygame.init()
pygame.mixer.music.load(song)
pygame.mixer.music.play()
time.sleep(10) #sleep for 10 seconds before moving on
pygame.mixer.music.stop()
thank you. i understand now. my mistake was:
pygame.init() -
i need
pygame.mixer.init()

Restarting every few minutes

I have the following code:
from alpha_vantage.timeseries import TimeSeries
import matplotlib.pyplot as plt
import sys
def stockchart(symbol):
ts = TimeSeries(key='1ORS1XLM1YK1GK9Y', output_format='pandas')
data, meta_data = ts.get_intraday(symbol=symbol, interval='1min', outputsize='full')
print (data)
I wanted to know how can i 'keep alive' so to say so that there a new request every say 5 mins for data? Is while loop the most efficient way to do this?
You mean like:
import time
while True:
ts = TimeSeries(key='1ORS1XLM1YK1GK9Y', output_format='pandas')
data, meta_data = ts.get_intraday(symbol=symbol, interval='1min', outputsize='full')
print (data)
time.sleep(300)
To achieve infinite recursion: Python "while" loops
And to wait for 5 minutes: time.sleep
Hope that answers your question!

Resources