gpt4 book ai didi

python - Dash Python - 每天动态更改默认日期

转载 作者:行者123 更新时间:2023-12-01 00:37:06 25 4
gpt4 key购买 nike

我正在使用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)

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

最佳答案

您必须将布局定义为函数

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来显示页面刷新时的时间小时:分钟:秒

<小时/>

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

关于python - Dash Python - 每天动态更改默认日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57651154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com