Dash Python – Changing default date dynamically everyday

Question:

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.

Asked By: Jeril

||

Answers:

You have to define layout as function

def 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=get_date() # for testing purpose
            # date=datetime.datetime.today().date() # Actual code
        ),
        html.Div(id='output-container-date-picker-single'),

        html.Div(datetime.datetime.now().strftime("%H:%M:%S"))
    ])

app.layout = layout

I added datetime to display time hours:minutes:seconds when page was refreshed.


Doc: Dash: Live Updating Components >> Updates on Page Load

Answered By: furas
        app.layout = html.Div([
            date_bar 
        ], id="page-content")
    
        date_bar = dbc.Row(
            [
                dcc.DatePickerSingle(
                    id='my-date-picker-single',
                    min_date_allowed=date(2023, 2, 1)
                )
            ],
            className="g-0 ms-auto flex-nowrap mt-3 mt-md-0",
            align="right",
        )
    
        @callback(
            Output('my-date-picker-single', 'date'),
            Input('page-content', 'value')
        )
        def change_date_dynamically(pageContent: str):
            # return (datetime.datetime.today() - datetime.timedelta(random.randint(1, 20))).date()
            return datetime.datetime.today().date()
        
        

This code works perfectly fine when there is no input needed and you want to change the date on page refresh.

Answered By: Maaz Sabahuddin
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.