【问题标题】:Dash Python - Changing default date dynamically everydayDash Python - 每天动态更改默认日期
【发布时间】:2019-08-26 02:30:27
【问题描述】:

我正在使用 Python 的 Dash 库来制作仪表板。我使用DatePickerSingle 选择日期,但默认日期始终是部署日期。以下是我的代码:

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)

默认日期在刷新期间不会更改,只有在部署或重新启动服务器时才会更改。有没有办法动态更改默认日期?请帮忙。谢谢。

【问题讨论】:

    标签: python plotly-dash


    【解决方案1】:

    你必须将布局定义为函数

    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
    

    我添加了datetime 以显示刷新页面时的时间hours:minutes:seconds


    文档:Dash: Live Updating Components >> Updates on Page Load

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-25
      • 1970-01-01
      • 1970-01-01
      • 2016-06-15
      • 2011-03-09
      • 1970-01-01
      相关资源
      最近更新 更多