簡體   English   中英

ValueError at / time data '' 與格式 '%Y-%m-%d' 不匹配

[英]ValueError at / time data '' does not match format '%Y-%m-%d'

我正在做一個項目,當用戶提到一個特定的日期范圍時,相應的數據就會被打印出來。 當提到特定日期時,頁面通過輸入類型 date 從用戶那里獲取輸入,date 的值傳遞給user_input_date_touser_input_date_to 但是當我執行時,我收到錯誤ValueError at / time data '' does not match format '%Y-%m-%d'

我的意見文件

def indexview(request):
    url=requests.get('https://data.covid19india.org/v4/min/timeseries.min.json')
    json_data=url.json()

    user_input_state=''
    user_input_date_from=''
    user_input_date_to=''
    user_data_type=''
    user_required_type=''
    if request.method == 'POST':
        user_input_state=request.POST.get('state')
        x=request.POST['date_from']
        user_input_date_to=request.POST['date_to']
        user_data_type=request.POST.get('data_period')
        user_required_type=request.POST.get('required_type')
        #To store dates list
    start_date =user_input_date_from
    end_date = user_input_date_to
    start_date_object = dt.datetime.strptime(start_date,"%Y-%m-%d").date()
    end_date_object = dt.datetime.strptime(end_date,"%Y-%m-%d").date()
    days = end_date_object - start_date_object
    dates=[]
    otp=[]
    for i in range(days.days+1):
        dates.append(str(start_date_object+dt.timedelta(days=i)))
    
    for i in dates:
        try:
            otp.append(json_data[user_input_state]['dates'][i][user_data_type][user_required_type])
        except KeyError:
            otp.append(0)
    
    dict_pass={
        'dates':dates,
        'otp':otp
        }
    return render(request,'index.html',dict_pass)

HTML 日期表單

 <input type="date" name="date_from"><br>  
 <input type="date" name="date_to">  

問題是,您正試圖從無效的用戶輸入(在您的情況下它是空字符串)創建格式為'%Y-%m-%d' datetime對象。

您應該首先驗證用戶輸入,然后執行業務邏輯。

您可以手動完成,或嘗試使用現有庫進行驗證(例如pydanticmarshmallow ...)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM