Dash Python - Changing default date dynamically everyday

I am using Python’s Dash library to make dashboard. I am using DatePickerSingle to select a date, but the default date is always the date of the deployment. The following is my code:

from datetime import datetime as dt
import dash
from dash.dependencies import Input, Output
import dash_html_components as html
import dash_core_components as dcc
import datetime

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']


def get_date():
    # Function to check for dynamic date change, for testing purpose only
    import random
    change = random.randint(1, 20)
    return (datetime.datetime.today() - datetime.timedelta(change)).date()

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
    dcc.DatePickerSingle(
        id='my-date-picker-single',
        min_date_allowed=dt(1995, 8, 5),
        max_date_allowed=dt(2017, 9, 19),
        date=get_date() # for testing purpose
        # date=datetime.datetime.today().date() # Actual code
    ),
    html.Div(id='output-container-date-picker-single')
])


@app.callback(
    Output('output-container-date-picker-single', 'children'),
    [Input('my-date-picker-single', 'date')])
def update_output(date):
    string_prefix = 'You have selected: '
    if date is not None:
        date = dt.strptime(date.split(' ')[0], '%Y-%m-%d')
        date_string = date.strftime('%B %d, %Y')
        return string_prefix + date_string


if __name__ == '__main__':
    app.run_server(debug=True)

The default date is not getting changed during refresh, it get changed only when the server is deployed or restarted. Is there a way to change the default date dynamically? Kindly help. Thanks.

Check out the “Updates on Page Load” section of the live updates page in the docs.

Basically you want to write a function and assign it to app.layout. This function will get called each time the page is refreshed. Something roughly like

def serve_layout():
    return html.Div([
        dcc.DatePickerSingle(
            id='my-date-picker-single',
            min_date_allowed=dt(1995, 8, 5),
            max_date_allowed=dt(2017, 9, 19),
            date=datetime.datetime.today().date() # Actual code
        ),
        html.Div(id='output-container-date-picker-single')
    ])


app.layout = serve_layout  # no parentheses, assign the function rather than the return value
1 Like

Thank you. It worked.

1 Like