pythonjsonpandasflask

the server responded with a status of 500 (INTERNAL SERVER ERROR) and ValueError: NaTType does not support timetuple


I am trying to make dashboard in flask by connecting it with SQL server and getting these errors. I confirm there are no null values and I checked by removing the column as well from query but still not working. Code is -

import pandas as pd
import pyodbc
from flask import Flask, render_template, jsonify
app = Flask(__name__)

# SQL Server Connection Details
conn_str = (
    "DRIVER={SQL Server};"
    "SERVER=xyz;"
    "DATABASE=xyz;"
    "UID=xyz;"
    "PWD=xyz;"
)

# Fetch Data from SQL Server
def fetch_data():
    try:
        conn = pyodbc.connect(conn_str)
        query = """
            SELECT TicketDate, Technician, Open_Tickets, Closed_Tickets, Created_Today, Closed_Today, Created_Hourly
            FROM Technician_Ticket_Stats
        """
        df = pd.read_sql(query, conn)
        conn.close()
        # Debugging logs
        print("Fetched data successfully:")
        print(df.head()) 
        df['TicketDate'] = df['TicketDate'].astype(str)  # Convert date for JSON
        return df.to_dict(orient="records")
    except Exception as e:
        print("Error fetching data:", e)  
        return []
@app.route("/")
def index():
    return render_template("index.html")
@app.route("/get_data")
def get_data():
    try:
        data = fetch_data()
        return jsonify(data)
    except Exception as e:
        return jsonify({"error": str(e)}), 500
if __name__ == "__main__":
    app.run(host='127.0.0.1', port=8050, debug=True)here

Solution

  • Add this line so that if there are NaT values in the 'TicketDate' column, it converts to None rather than throwing an error.

    df['TicketDate'] = df['TicketDate'].fillna(pd.NaT).apply(
        lambda x: x.strftime('%Y-%m-%d') if pd.notna(x) else None
    )