Create a Python script that connects to a Cassandra database, creates a keyspace and table for storing weather data (temperature, humidity, pressure), inserts sample data into the table, and queries the data to find the average temperature for a specified date range.
PLAINFORMAT
from cassandra.cluster import Cluster
from datetime import datetime

# Connect to Cassandra database
cluster = Cluster(['127.0.0.1'])
session = cluster.connect()

# Create a keyspace for storing weather data
session.execute("""
    CREATE KEYSPACE IF NOT EXISTS weather_data
    WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}
""")

# Use the created keyspace
session.set_keyspace('weather_data')

# Create a table for storing temperature, humidity, and pressure
session.execute("""
    CREATE TABLE IF NOT EXISTS weather (
        date timestamp,
        temperature float,
        humidity float,
        pressure float,
        PRIMARY KEY (date)
    )
""")

# Insert sample data into the table
sample_data = [
    (datetime(2021, 10, 1), 20.5, 60.0, 1013.0),
    (datetime(2021, 10, 2), 21.0, 55.0, 1012.0),
    (datetime(2021, 10, 3), 19.5, 65.0, 1014.0),
]

for data in sample_data:
    session.execute(
        """
        INSERT INTO weather (date, temperature, humidity, pressure)
        VALUES (%s, %s, %s, %s)
        """,
        data
    )

# Query the data to find the average temperature for a specified date range
start_date = datetime(2021, 10, 1)
end_date = datetime(2021, 10, 3)

rows = session.execute(
    """
    SELECT AVG(temperature) as avg_temperature
    FROM weather
    WHERE date >= %s AND date <= %s
    ALLOW FILTERING
    """,
    (start_date, end_date)
)

for row in rows:
    print(f"Average temperature between {start_date} and {end_date}: {row.avg_temperature}")

# Close the connection
cluster.shutdown()