Created
May 19, 2022 14:06
-
-
Save asehmi/263f00a6ca94a007f67ff182053c5b94 to your computer and use it in GitHub Desktop.
Setting Streamlit widget values via callbacks (dates examples)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Based on discussion here: https://discuss.streamlit.io/t/how-to-work-date-input-with-shortcuts/25377/3 | |
import streamlit as st | |
from datetime import datetime as dt | |
import calendar | |
state = st.session_state | |
if 'message' not in state: | |
state.message = '' | |
def _change_date_cb(option): | |
if option == 'Today': | |
state.key_start_date = dt.now() | |
state.key_end_date = dt.now() | |
elif option == 'Week': | |
cal = calendar.monthcalendar(dt.now().year, dt.now().month) | |
tdy = dt.now().day | |
for i in range(len(cal)): | |
if tdy in cal[i]: | |
state.key_start_date = dt(dt.now().year, dt.now().month, cal[i][0]) | |
state.key_end_date = dt(dt.now().year, dt.now().month, cal[i][6]) | |
break | |
elif option == 'Month': | |
state.key_start_date = dt(dt.now().year, dt.now().month, 1) | |
state.key_end_date = dt(dt.now().year, dt.now().month, calendar.monthrange(dt.now().year, dt.now().month)[1]) | |
state.message = option | |
c1, c2 = st.columns(2) | |
start_date = c1.date_input('Start Date', key='key_start_date') | |
end_date = c2.date_input('End Date', key='key_end_date') | |
c1, c2, c3 = st.columns(3) | |
c1.button('Today', on_click=_change_date_cb, args=('Today',)) | |
c2.button('Week', on_click=_change_date_cb, args=('Week',)) | |
c3.button('Month', on_click=_change_date_cb, args=('Month',)) | |
if state.message: | |
st.write('---') | |
st.write(f'Dates set for {state.message}') | |
st.write(f'`Start: {start_date:%d-%b-%y} | End: {end_date:%d-%b-%y}`') |
Author
asehmi
commented
May 19, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment