Date type Attribute Error, TypeError and all possible errors

Hi community,
I am trying to build Manufacturing resource planning system with Python and Dash…
I am using SQLAlchemy to connect to MySQL and write to it. i am having all sorts of fields and type checking’s, but only one that is giving me a headache, starting from input filed formatting, to errors is Date input field…

Here is my input fields, callback and function:
html.H1(“MRP App”),
html.H2(“Master production Scheduling”),
dcc.Input(id=“mps-product-id-input”, type=“number”, placeholder=“Product ID”),
dcc.Input(id=“start-date-input”, type=“Date”, placeholder=“yyyy-mm-dd”),
dcc.Input(id=“end-date-input”, type=“Date”, placeholder=“yyyy-mm-dd”),
dcc.Input(id=“mps-quantity-input”, type=“number”, placeholder=“Quantity”),
dcc.Input(id=“resources-input”, type=“text”, placeholder=“Resources required”),
html.Button(“Create Production Schedule”, id=“create-schedule-button”),
html.Div(id=“schedule-output”),

@app.callback(
Output(“schedule-output”,“children”),
Input(“create-schedule-button”, “n_clicks”),
[
Input(“mps-product-id-input”, “value”),
Input(“start-date-input”, “value”),
Input(“end-date-input”, “value”),
Input(“mps-quantity-input”, “value”),
Input(“resources-input”, “value”)
],
)

def create_production_schedule(n_clicks, product_id, start_date, end_date, quantity, resources):
if n_clicks and product_id and start_date and end_date and quantity and resources:
try:
print(“Start Date:”, start_date)
print(“End Date:”, end_date)
start_date = datetime.strptime(start_date, ‘%Y-%m-%d’).date()
end_date = datetime.strptime(end_date, ‘%Y-%m-%d’).date()
print(“Parsed Start Date:”, start_date)
print(“Parsed End Date:”, end_date)
product_id = int(product_id)
quantity = int(quantity)
except ValueError as e:
print(“ValueError:”, str(e))
return html.Div(“Invalid input. Please provide valid values.”)

    query = "INSERT INTO m_prod_schedule (product_id, start_date, end_date, quantity, resources_required) VALUES (%s, %s, %s, %s, %s)"
    values = (product_id, start_date, end_date, quantity, resources)
    execute_query(query, values)
    return html.Div("Production schedule created successfully!")
else:
    return html.Div("Please fill in all the input fields.")

Firstly, input field for date is not formatting as yyyy-mm-dd even when I enforce pattern
with date type:
dcc.Input(id=“end-date-input”, type=“Date”, placeholder=“yyyy-mm-dd”, pattern=r"\d{4}-\d{2}-\d{2}"),
Pattern shows when type is text, but that raise an error for my function…

Not to write here indefinitely, depending of what i change in my def, i get different errors with datetime, with date, with fromisoformat… or what ever else that i try…
AttributeError: module ‘datetime’ has no attribute ‘strptime’
TypeError: ‘<’ not supported between instances of ‘datetime.date’ and ‘int’

If you can help me with input formatting and how to fix this date type to pass to my database , it will be mostly appreciated!

Hi @DataBora , for the Date Input you could check out the nice dash-mantine-components library.

1 Like

Based on doc example, it seems that the input type for the date-range-picker component is a list of strings representing dates in the format YYYY-MM-DD

html.Div(
    [
        dmc.DateRangePicker(
            id="date-range-picker",
            label="Date Range",
            description="You can also provide a description",
            minDate=date(2020, 8, 5),
            value=[datetime.now().date(), datetime.now().date() + timedelta(days=5)],
            style={"width": 330},
        ),
        dmc.Space(h=10),
        dmc.Text(id="selected-date-date-range-picker"),
    ]
)


@callback(
    Output("selected-date-date-range-picker", "children"),
    Input("date-range-picker", "value"),
)
def update_output(dates):
    prefix = "You have selected: "
    if dates:
        return prefix + "   -   ".join(dates)
    else:
        raise PreventUpdate

When I make test example:

connection_string = f"mysql+pymysql://{user}:{password}@{host}:{port}/{database}"

# Create the SQLAlchemy engine
engine = create_engine(connection_string)

app = dash.Dash(__name__)

app.layout = html.Div(
    children=[
        html.H1("MRP App"),
        html.H2("Master production Scheduling"),
        dcc.Input(id="mps-product-id-input", type="number", placeholder="Product ID"),
        html.Div(
            [
                dcc.DatePickerRange(
                    id="date-range-picker",
                    start_date_placeholder_text="Start Date",
                    end_date_placeholder_text="End Date",
                    min_date_allowed=date(2020, 8, 5),
                    max_date_allowed=date.today() + timedelta(days=365),
                    initial_visible_month=date.today(),
                    style={"width": 330},
                ),
                html.Div(id="selected-date-date-range-picker"),
            ]
        ),
        dcc.Input(id="mps-quantity-input", type="number", placeholder="Quantity"),
        dcc.Input(id="resources-input", type="text", placeholder="Resources required"),
        html.Button("Create Production Schedule", id="create-schedule-button"),
        html.Div(id="schedule-output"),
    ]
)


@app.callback(
    Output("schedule-output", "children"),
    Input("create-schedule-button", "n_clicks"),
    [
        Input("mps-product-id-input", "value"),
        Input("date-range-picker", "start_date"),
        Input("date-range-picker", "end_date"),
        Input("mps-quantity-input", "value"),
        Input("resources-input", "value"),
    ],
)
def create_production_schedule(n_clicks, product_id, start_date, end_date, quantity, resources):
    if n_clicks and product_id and start_date and end_date and quantity and resources:
        try:
            print("Start Date:", start_date)
            print("End Date:", end_date)
            start_date = datetime.strptime(start_date, '%Y-%m-%d').date()
            end_date = datetime.strptime(end_date, '%Y-%m-%d').date()
            print("Parsed Start Date:", start_date)
            print("Parsed End Date:", end_date)
            product_id = int(product_id)
            quantity = int(quantity)
        except ValueError as e:
            print("ValueError:", str(e))
            return html.Div("Invalid input. Please provide valid values.")

        query = "INSERT INTO m_prod_schedule (product_id, start_date, end_date, quantity, resources_required) VALUES (%s, %s, %s, %s, %s)"
        values = (product_id, start_date, end_date, quantity, resources)
        execute_query(query, values)
        return html.Div("Production schedule created successfully!")
    else:
        return html.Div("Please fill in all the input fields.")


def execute_query(query, values=None):
    with engine.connect() as conn:
        if values is None:
            # Single query without values
            result = conn.execute(text(query))
        else:
            if isinstance(values, list):
                # Multiple queries with values
                result = conn.execute(text(query), values)
            else:
                # Single query with values
                result = conn.execute(text(query), [values])
        return result



if __name__ == "__main__":
    app.run_server(debug=False)

I get similar errors…One of which is: TypeError: ‘<’ not supported between instances of ‘datetime.date’ and ‘int’

My guess is that you are trying to compare start date end end date and the order of arguments might be mixed up somewhere.

Where do you do the < comparison ?

In what case values can be of type list?

And what does the function text do?

I am fully retarded…, I didn’t made comparison…
Here is the function that works with comparison:

def create_production_schedule(n_clicks, product_id, start_date, end_date, quantity, resources):
    if n_clicks and product_id and start_date and end_date and quantity and resources:
        try:
            print("Start Date:", start_date)
            print("End Date:", end_date)
            start_date = datetime.strptime(start_date, '%Y-%m-%d').date()
            end_date = datetime.strptime(end_date, '%Y-%m-%d').date()
            print("Parsed Start Date:", start_date)
            print("Parsed End Date:", end_date)
            product_id = int(product_id)
            quantity = int(quantity)

            # Compare start date and end date
            if start_date > end_date:
                return html.Div("Start date cannot be greater than end date.")

        except ValueError as e:
            print("ValueError:", str(e))
            return html.Div("Invalid input. Please provide valid values.")

        query = "INSERT INTO m_prod_schedule (product_id, start_date, end_date, quantity, resources_required) " \
                "VALUES (:product_id, :start_date, :end_date, :quantity, :resources_required)"
        values = {
            "product_id": product_id,
            "start_date": start_date,
            "end_date": end_date,
            "quantity": quantity,
            "resources_required": resources
        }
        execute_query(query, values)
        return html.Div("Production schedule created successfully!")
    else:
        return html.Div("Please fill in all the input fields.")

For 2 days I am hitting the wall…Thank you my friend!

1 Like

Well, at least you found the cause for the error, happy to be of help.

1 Like

If values is not a list, it means it executing a single query with a single set of values. In this case, the values parameter is wrapped in a list before passing it to the conn.execute method.
If value is a list, it means you’re executing multiple queries, each with a different set of values. Each element in the values list represents a set of values for a specific query.
In this case, the conn.execute method is called with values list directly

text function is a helper function in SQLAlchemy to create a TextClause object, which represents a SQL statement…

1 Like