Related
import requests
import telegram
import json
from telegram.ext import Updater, CommandHandler
import time
import sys
import pandas as pd
from apscheduler.schedulers.background import BlockingScheduler
from apscheduler.jobstores.base import JobLookupError
dt = requests.get('https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD,EUR')
print(dt.text)
price_now = dt.json()
bot_token = "5668522544:AAFqNFcgd5wDBtQbJBhRayfPx9VpVPVjcyQ"
Cointimeline = telegram.Bot(token=bot_token)
updates = Cointimeline.getUpdates()
for i in updates:
print(i.message)
class Chatbot:
def __init__(self, token):
self.core = telegram.Bot(token)
self.updater = Updater(token)
self.id = 5734902861
def sendmsg(self, text):
self.core.sendmsg(chat_id=self.id, text=text)
def stop(self):
self.updater.stop()
class Alert(Chatbot):
def __init__(self):
self.token = '5668522544:AAFqNFcgd5wDBtQbJBhRayfPx9VpVPVjcyQ'
Chatbot.__init__(self, self.token)
self.updater.stop()
def controller(self, cmd, func):
self.updater.dispatcher.controller(CommandHandler(smd, func))
def start(self):
self.sendMessage('')
aps = BlockingScheduler()
def push():
dt = requests.get("https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD,EUR")
ALERTBOT = Alert()
ALERTBOT.sendmsg(dt.text)a
price_now = pd.DataFrame({"USD": {list(dt.json().values())[0]}, "EUR": [list(dt.json().values())[1]]})
data = pd.read_csv("ALERTBOT.csv")
data = data.append(price_now, sort=True)
data = data.loc[:, 'USD':'EUR']
data.to_csv("ALERTBOT.csv")
aps.add_job(push, 'interval', seconds=60)
aps.start()
The error continues to occur.
PytzUsageWarning: The zone attribute is specific to pytz's interface; please migrate to a new time zone provider. For more details on how to do so, see https://pytz-deprecation-shim.readthedocs.io/en/latest/migration.html
if obj.zone == 'local':
The error is caused by the pytz library being out of date. You can solve the problem by updating the library:
pip install --upgrade pytz
I'm trying to interact DatePicker with SelectionRangeSlider widgets. So far I could manage to link the slider with the DatePicker, but I'm getting trouble with the opposite way.
With this code the period slider updates the DatePicker:
from datetime import datetime
import pandas as pd
import ipywidgets as widgets
start_date = datetime(2021, 7, 1)
end_date = datetime(2021, 7, 5)
dates = pd.date_range(start_date, end_date, freq='D')
options = [(date.strftime(' %d %b %Y '), date) for date in dates]
pick_start = widgets.DatePicker(
description='',
disabled=False,
value = start_date
)
pick_end = start_day = widgets.DatePicker(
description='',
disabled=False,
value=end_date
)
selection_range_slider = widgets.SelectionRangeSlider(
options=options,
index=(0, len(options) - 1),
description='Period',
orientation='horizontal',
layout=widgets.Layout(width='100%', padding='35px')
)
def update_pick(*args):
pick_start.value = datetime.strptime(selection_range_slider.value[0].strftime("%Y-%m-%d"), "%Y-%m-%d")
pick_end.value = datetime.strptime(selection_range_slider.value[1].strftime("%Y-%m-%d"), "%Y-%m-%d")
def update_slider(*args):
selection_range_slider.value[0] = pick_start.value.strftime("%Y-%m-%d")
selection_range_slider.value[1] = pick_end.value.strftime("%Y-%m-%d")
selection_range_slider.observe(update_pick, 'value')
pick_start.observe(update_slider, 'value')
pick_end.observe(update_slider, 'value')
center_layout = widgets.Layout(display='flex',
align_items='center',
width='100%')
day = widgets.HBox(children=[pick_start, selection_range_slider, pick_end], layout=center_layout)
display(day)
Also try with this function without result:
def update_slider(*args):
start_date = datetime(pick_start.value.year, pick_start.value.month, pick_start.value.day)
end_date = datetime(pick_end.value.year, pick_end.value.month, pick_end.value.day)
dates = pd.date_range(start_date, end_date, freq='D')
options = [(date.strftime(' %d %b %Y '), date) for date in dates]
selection_range_slider.value[0] = options[0]
selection_range_slider.value[1] = options[len(options)-1]
Need help interacting DatePicker with SelectionRangeSlider
Thanks!
you have done a nice job of creating a standalone question here, thanks. A couple suggestions for your next Q to speed up an answer.
Please include your imports, I can't run your code without them:
from datetime import datetime
import pandas as pd
import ipywidgets as widgets
Please post any error messages that you see when your code runs. I got a ValueError which would have improved the question even more.
The error said there was an issue assigning to an index of a tuple, Here's my solution.
Assign the whole tuple directly, you cannot update index 0 and then index 1 of your selection_range_slider
Use raw datetimes to pass between widgets, your mixed string conversions were causing some issues. You can still change how the dates are displayed in the slider by using a dictionary for options.
from datetime import datetime
import pandas as pd
import ipywidgets as widgets
start_date = datetime(2021, 7, 1)
end_date = datetime(2021, 7, 5)
dates = pd.date_range(start_date, end_date, freq='D')
options = {date.strftime(' %d %b %Y '): date for date in dates}
pick_start = widgets.DatePicker(
description='',
disabled=False,
value = start_date
)
pick_end = start_day = widgets.DatePicker(
description='',
disabled=False,
value=end_date
)
selection_range_slider = widgets.SelectionRangeSlider(
options=options,
index=(0, len(options) - 1),
description='Period',
orientation='horizontal',
layout=widgets.Layout(width='100%', padding='35px')
)
def update_pick(*args):
pick_start.value = selection_range_slider.value[0]
pick_end.value = selection_range_slider.value[1]
def update_slider(*args):
selection_range_slider.value = (pick_start.value, pick_end.value)
selection_range_slider.observe(update_pick, 'value')
pick_start.observe(update_slider, 'value')
pick_end.observe(update_slider, 'value')
center_layout = widgets.Layout(display='flex',
align_items='center',
width='100%')
day = widgets.HBox(children=[pick_start, selection_range_slider, pick_end], layout=center_layout)
display(day)
I'm not sure why my datatime is being printed the way it is. I'm expecting the format of "%Y-%M-%D" (2020-05-11)
import datetime
from pyspark.sql.functions import *
currentdate = datetime.datetime.now().strftime("%Y-%M-%D")
print(dateValue)
Output:
2020-09-05/11/20
Try with %Y-%m-%d instead of %Y-%M-%D
currentdate = datetime.datetime.now().strftime("%Y-%m-%d")
print (currentdate)
#2020-05-11
#or using spark sql
currentdate=spark.sql("select string(current_date)").collect()[0][0]
print(currentdate)
#2020-05-11
I am new to Bokeh and looking for solution to label each data point. Replicating the examples shown in documents, I could not find solutions with X axis being datetime.
import pandas as mypd
from bokeh.models import LabelSet , ColumnarDataSource
from bokeh.plotting import figure, output_file, show
date_1 = ['2020-01-01', '2020-01-02','2020-01-03','2020-01-04','2020-01-05']
sal = mypd.DataFrame(date_1)
sal.columns = ["Date_1"]
sal['Sales'] = [15,25,36,17,4]
sal['Date_1'] = mypd.to_datetime(sal['Date_1'])
p= figure(x_axis_type = "datetime")
p.line(x =sal['Date_1'] ,y = sal['Sales'])
lab = LabelSet(x = sal['Date_1'], y = sal['Sales'], text = sal['Sales'])
p.add_layout(lab)
show(p)
It is throwing the error
ValueError: expected an element of either String, Dict(Enum('expr', 'field', 'value', 'transform'), Either(String, Instance(Transform), Instance(Expression), Float)) or Float, got 0 2020-01-01
I understand the error is because x axis take numerical data for labelset.
Is my understanding correct ?
If yes what is the workaround ?
I tried with similar queries but could not find a solution for myself.
Similar Query
And this
The simplest solution is to just use a common data source. It also prevents you from embedding the data twice.
import pandas as pd
from bokeh.models import LabelSet, ColumnDataSource
from bokeh.plotting import figure, show
sal = (pd.DataFrame({'Date_1': pd.to_datetime(['2020-01-01', '2020-01-02', '2020-01-03', '2020-01-04', '2020-01-05']),
'Sales': [15, 25, 36, 17, 4]})
.set_index('Date_1'))
ds = ColumnDataSource(sal)
p = figure(x_axis_type="datetime")
p.line(x='Date_1', y='Sales', source=ds)
lab = LabelSet(x='Date_1', y='Sales', text='Sales', source=ds)
p.add_layout(lab)
show(p)
I use python 3.6 and sqlite3, and I have a problem when I want to read the content of the table between 2 variables
first, when I use two string format dates ("2019-01-01" and "2019-05-20") the following code works correctly :
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from tkinter import *
import time
import calendar
import sqlite3
import datetime
fen = Tk()
fen.title('ILS system ')
fen.resizable(0,0)
largeur=920
hauteur=660
fen.geometry('{}x{}+0+0'.format(largeur,hauteur))
def CreateTable_releves():
conn1_releves = sqlite3.connect('bdd/test.db')
curseur1_releves = conn1_releves.cursor()
curseur1_releves.execute('''CREATE TABLE IF NOT EXISTS releves (id INTEGER PRIMARY KEY,time_releves TEXT NOT NULL, monitor1_releves TEXT NOT NULL,monitor2_releves TEXT NOT NULL)''')
curseur1_releves.close()
def Add_To_Table_releves():
time_releves_get = str(date_choisie_ils35R)
monitor1_releves_get = str(ent_releves_mesure_mon1_axe_loc35R.get())
monitor2_releves_get = str(ent_releves_mesure_mon2_axe_loc35R.get())
conn2_releves = sqlite3.connect('bdd/test.db')
curseur2_releves = conn2_releves.cursor()
curseur2_releves.execute('''INSERT INTO releves (time_releves,monitor1_releves,monitor2_releves) VALUES (?,?,?)''',(time_releves_get,monitor1_releves_get,monitor2_releves_get))
conn2_releves.commit()
curseur2_releves.close()
# CreateTable_releves()
def monitoring () :
fen_monitoring=Toplevel(fen)
fen_monitoring.title('ddm axe')
fen_monitoring.geometry('450x400+300+150')
s= Scrollbar(fen_monitoring)
T= Text(fen_monitoring,bg='powder blue',width=450,height=400)
s.pack(side=RIGHT, fill=Y)
T.pack(side=LEFT, fill=Y)
s.config(command=T.yview)
T.config(yscrollcommand=s.set)
def update_releves():
T.delete('1.0', END)
T.update()
conn = sqlite3.connect('bdd/test.db')
curseur = conn.cursor()
for resultats in curseur.execute('SELECT * FROM releves where time_releves between "2019-01-01" AND "2019-05-20" ORDER BY time_releves DESC'):
contenu_table_releves= str(resultats[1])+"\t\t"+ str(resultats[2])+"\t\t"+ str(resultats[3])+"\n"
T.insert(END,contenu_table_releves)
T.after(1000,update_releves)
curseur.close()
update_releves()
bt=Button(fen,text='click on\nthe button', command=monitoring)
bt.pack()
here is the image of the contents of the toplevel window :
enter image description here
but if I modify the code by input two variables (first_day) and (last_day) in the sql requet :
for resultats in curseur.execute('SELECT * FROM releves where time_releves between "first_day" AND "last_day" ORDER BY time_releves DESC'):
there is the complet modify code :
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from tkinter import *
import time
import calendar
import sqlite3
import datetime
fen = Tk()
fen.title('ILS system ')
fen.resizable(0,0)
largeur=920
hauteur=660
fen.geometry('{}x{}+0+0'.format(largeur,hauteur))
#to calculate first and last day of the month:
now = datetime.datetime.now()
start_month = datetime.datetime(now.year, now.month, 1)
date_on_next_month = start_month + datetime.timedelta(35)
start_next_month = datetime.datetime(date_on_next_month.year, date_on_next_month.month, 1)
last_day_month = start_next_month - datetime.timedelta(1)
last_day=last_day_month.strftime('%Y-%m-%d')
first_day=start_month = datetime.datetime(now.year, now.month, 1).strftime('%Y-%m-%d')
def CreateTable_releves():
conn1_releves = sqlite3.connect('bdd/test.db')
curseur1_releves = conn1_releves.cursor()
curseur1_releves.execute('''CREATE TABLE IF NOT EXISTS releves (id INTEGER PRIMARY KEY,time_releves TEXT NOT NULL, monitor1_releves TEXT NOT NULL,monitor2_releves TEXT NOT NULL)''')
curseur1_releves.close()
def Add_To_Table_releves():
time_releves_get = str(date_choisie_ils35R)
monitor1_releves_get = str(ent_releves_mesure_mon1_axe_loc35R.get())
monitor2_releves_get = str(ent_releves_mesure_mon2_axe_loc35R.get())
conn2_releves = sqlite3.connect('bdd/test.db')
curseur2_releves = conn2_releves.cursor()
curseur2_releves.execute('''INSERT INTO releves (time_releves,monitor1_releves,monitor2_releves) VALUES (?,?,?)''',(time_releves_get,monitor1_releves_get,monitor2_releves_get))
conn2_releves.commit()
curseur2_releves.close()
# CreateTable_releves()
def monitoring () :
fen_monitoring=Toplevel(fen)
fen_monitoring.title('ddm axe')
fen_monitoring.geometry('450x400+300+150')
s= Scrollbar(fen_monitoring)
T= Text(fen_monitoring,bg='powder blue',width=450,height=400)
s.pack(side=RIGHT, fill=Y)
T.pack(side=LEFT, fill=Y)
s.config(command=T.yview)
T.config(yscrollcommand=s.set)
def update_releves():
T.delete('1.0', END)
T.update()
conn = sqlite3.connect('bdd/test.db')
curseur = conn.cursor()
for resultats in curseur.execute('SELECT * FROM releves where time_releves between "first_day" AND "last_day" ORDER BY time_releves DESC'):
contenu_table_releves= str(resultats[1])+"\t\t"+ str(resultats[2])+"\t\t"+ str(resultats[3])+"\n"
T.insert(END,contenu_table_releves)
T.after(1000,update_releves)
curseur.close()
update_releves()
bt=Button(fen,text='click on\nthe button', command=monitoring)
bt.pack()
the toplevel window appear but empty like in the next picture :
enter image description here
I modified the code so that it is clearer by integrating widget (entry, button), and then I added the setpoint of "R Spark". I had as a result the following code which apparently works for the moment. (I will redo other tests soon)
if there are any comments about this new this would be welcome.
The new code:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from tkinter import *
import time
import calendar
import sqlite3
import datetime
fen = Tk()
fen.title('ILS system ')
fen.resizable(0,0)
largeur=920
hauteur=660
fen.geometry('{}x{}+0+0'.format(largeur,hauteur))
#to calculate first and last day of the month:
now = datetime.datetime.now()
start_month = datetime.datetime(now.year, now.month, 1)
date_on_next_month = start_month + datetime.timedelta(35)
start_next_month = datetime.datetime(date_on_next_month.year, date_on_next_month.month, 1)
last_day_month = start_next_month - datetime.timedelta(1)
last_day=last_day_month.strftime('%Y-%m-%d')
first_day=start_month = datetime.datetime(now.year, now.month, 1).strftime('%Y-%m-%d')
def CreateTable_releves():
conn1_releves = sqlite3.connect('bdd/test/test.db')
curseur1_releves = conn1_releves.cursor()
curseur1_releves.execute('''CREATE TABLE IF NOT EXISTS releves (id INTEGER PRIMARY KEY,time_releves TEXT NOT NULL, monitor1_releves TEXT NOT NULL,monitor2_releves TEXT NOT NULL)''')
curseur1_releves.close()
def Add_To_Table_releves():
time_releves_get = str(date_choisie.get())
monitor1_releves_get = str(ent_mon1_mesure.get())
monitor2_releves_get = str(ent_mon2_mesure.get())
conn2_releves = sqlite3.connect('bdd/test/test.db')
curseur2_releves = conn2_releves.cursor()
curseur2_releves.execute('''INSERT INTO releves (time_releves,monitor1_releves,monitor2_releves) VALUES (?,?,?)''',(time_releves_get,monitor1_releves_get,monitor2_releves_get))
conn2_releves.commit()
curseur2_releves.close()
CreateTable_releves()
def monitoring () :
fen_monitoring=Toplevel(fen)
fen_monitoring.title('ddm axe')
fen_monitoring.geometry('450x400+300+150')
s= Scrollbar(fen_monitoring)
T= Text(fen_monitoring,bg='powder blue',width=450,height=400)
s.pack(side=RIGHT, fill=Y)
T.pack(side=LEFT, fill=Y)
s.config(command=T.yview)
T.config(yscrollcommand=s.set)
def update_releves():
T.delete('1.0', END)
T.update()
conn = sqlite3.connect('bdd/test/test.db')
curseur = conn.cursor()
for resultats in curseur.execute('SELECT * FROM releves where time_releves between ? AND ? ORDER BY time_releves DESC;', (first_day, last_day)):
contenu_table_releves= str(resultats[1])+"\t\t"+ str(resultats[2])+"\t\t"+ str(resultats[3])+"\n"
T.insert(END,contenu_table_releves)
T.after(1000,update_releves)
curseur.close()
update_releves()
ent_mon1_mesure=StringVar()
ent_mon2_mesure=StringVar()
date_choisie=StringVar()
ent_mon1=Entry(fen,textvariable=ent_mon1_mesure)
ent_mon1.pack(side=LEFT,anchor=NW,padx=10,pady=10)
ent_mon2=Entry(fen,textvariable=ent_mon2_mesure)
ent_mon2.pack(side=LEFT,anchor=NW,padx=10,pady=10)
ent_time_releve=Entry(fen,textvariable=date_choisie)
ent_time_releve.pack(side=LEFT,anchor=NW,padx=10,pady=10)
bt_valider=Button(fen,text='valider', command=Add_To_Table_releves)
bt_valider.pack(side=LEFT,padx=10,pady=10)
bt_monitoring=Button(fen,text='afficher monitoring', command=monitoring)
bt_monitoring.pack(side=LEFT,padx=10,pady=10)
fen.mainloop()
Thanks R Spark for help