Météo Montpellier

Code
# Importation des bibliothèques nécessaires
import numpy as np
import statistics
import requests
import datetime
from dateutil.relativedelta import relativedelta

# Initialisation des dates de début et de fin pour l'extraction des données
date_debut = datetime.datetime.now() - relativedelta(days=2)
date_fin = date_debut + relativedelta(days=6)

# Formatage des dates pour l'URL de l'API
date_debut_formattee = date_debut.strftime('%Y-%m-%d') 
date_fin_formattee = date_fin.strftime('%Y-%m-%d')  

# Construction de l'URL pour l'API open-meteo avec les critères spécifiés
url = f"https://api.open-meteo.com/v1/meteofrance?latitude=43.6109&longitude=3.8763&hourly=temperature_2m,,relative_humidity_2m,precipitation&daily=weathercode,temperature_2m_max,temperature_2m_min,wind_speed_10m_max,precipitation_sum&timezone=Europe%2FLondon&start_date={date_debut_formattee}&end_date={date_fin_formattee}"

# Récupération des données depuis l'API
response = requests.get(url)
data = response.json()

# Initialisation des tableaux pour les différents paramètres météorologiques
humidity = data["hourly"]["relative_humidity_2m"]
precipitation = data["daily"]["precipitation_sum"]
precipitation_h = data["hourly"]["precipitation"]
wind = data["daily"]["wind_speed_10m_max"]
tempmin = data["daily"]["temperature_2m_min"]
tempmax = data["daily"]["temperature_2m_max"]
icon = data["daily"]["weathercode"]

# Fonction pour formater la date en fonction de l'index donné
def date(i):
    
    d = datetime.datetime.now() + relativedelta(days=i)
    return f"{d.day}-{d.month}-{d.year}"


# Initialisation des tableaux pour l'humidité moyenne et un tableau 2D pour les valeurs horaires de l'humidité
meanhumidity = np.zeros(7)
tab = np.zeros((7, 24))
t= 0
# Remplissage du tableau 2D avec les valeurs horaires de l'humidité
for i in range(7):
    for j in range(24):
        if humidity[t] is None:
            tab[i, j] = tab[i, j - 1] if j > 0 else 0
        else:
            tab[i, j] = humidity[t]
        t += 1
# Calcul de l'humidité moyenne pour chaque jour
for i in range(7):
    meanhumidity[i] = round(statistics.mean(tab[i]), 0)  

# Fonction pour obtenir le jour de la semaine en fonction de l'index donné
def index(i):
    
    jours_semaine = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
    return jours_semaine[(datetime.datetime.now().weekday() + i) % 7]  

# Fonction pour mapper le code météo à l'icône correspondante
def iconkey(i):
    """
    Association de chaque code WBO à un pictogramme correspondant. Retourne le chemin d'accès au pictogramme par une chaîne de caractères. Version daily.
    """
    code = icon[i]

    if code == 0:
        return "icon/wi-day-sunny.svg"
    elif code == 1:
        return "icon/wi-day-sunny-overcast.svg"
    elif code == 2:
        return "icon/wi-day-cloudy.svg"
    elif code == 3:
        return "icon/wi-cloud.svg"
    elif code in [45, 48]:
        return "icon/wi-fog.svg"
    elif code in [51, 53, 55, 56, 57]:
        return "icon/wi-sprinkle.svg"
    elif code in [61, 81, 82]:
        return "icon/wi-showers.svg"
    elif code == 63:
        return "icon/wi-rain-wind.svg"
    elif code in [65, 66, 67]:
        return "icon/wi-rain.svg"
    elif code in [71, 73, 75, 85, 86]:
        return "icon/wi-snow.svg"
    elif code in [95, 96]:
        return "icon/wi-storm-showers.svg"
    elif code == 99:
        return "icon/wi-thunderstorm.svg"
    else:
        return "icon/wi-moon-new.svg"

# Fonction pour afficher l'icône de précipitation en fonction de l'intensité
def iconrain(i):
    
    """
    Retourne une image sous format HTML correspondant à l'intensité des précipitations.
    """
    if not isinstance(precipitation[i], float):
        return ""

    intensity = precipitation[i]

    if 0 < intensity <= 2:
        return f'<img src="icon/wi-raindrop.svg" width="20" height="20" />'
    elif intensity > 2:
        return f'<img src="icon/wi-raindrops.svg" width="40" height="40" />'
    else:
        return ""  
# Calcule la somme des 24 dernières valeurs de precipitation_h
precipitation_h = [0 if value is None else value for value in precipitation_h]
precipitationd = sum(precipitation_h[-24:])        

# Importation des bibliothèques nécessaires pour afficher du HTML et tabuler les données
from IPython.display import HTML
from tabulate import tabulate
res = f"""
<table class= "table1-style">
    <thead>
    <tr>  
        <th  style="border-top-left-radius : 20px 20px"> Days </th>
        <th>  {index(-2)} <br> <small> {date(-2)} </small></th>
        <th>  {index(-1)} <br> <small>{date(-1)}</small></th>
        <th>   <a  style="text-decoration:none"> Today <br> <small>{date(0)}</small> </a></th>
        <th>  {index(1)} <br> <small>{date(1)}</small></th>
        <th>  {index(2)} <br> <small>{date(2)}</small></th>
        <th>  {index(3)} <br> <small>{date(3)}</small></th>
        <th  style="border-top-right-radius : 20px 20px" >  {index(4)} <br> <small>{date(4)}</small></th>
    </tr>
    </thead>
    <tbody>
    <tr> 
        <td>  </td>
        <td> <img src={iconkey(0)} width="50"
  height="50" /> </td>
        <td> <img src={iconkey(1)} width="50"
  height="50" /> </td>
        <td> <img src={iconkey(2)} width="50"
  height="50" /> </td>
        <td> <img src={iconkey(3)} width="50"
  height="50" /> </td>
        <td> <img src={iconkey(4)} width="50"
  height="50" /> </td>
        <td> <img src={iconkey(5)} width="50"
  height="50" /> </td>
        <td> <img src={iconkey(6)} width="50"
  height="50" /> </td>
    </tr>
    <tr> 
        <td> Temp Max (°C) </td>
        <td style =" background-color : rgba(255, 165, 80, 0.5); font-weight: bold;" > {tempmax[0]}°C </td>
        <td style =" background-color : rgba(255, 165, 80, 0.5);font-weight: bold;" > {tempmax[1]}°C </td>
        <td style =" background-color : rgba(255, 165, 80, 0.5);font-weight: bold;" > {tempmax[2]}°C </td>
        <td style =" background-color : rgba(255, 165, 80, 0.5);font-weight: bold;" > {tempmax[3]}°C </td>
        <td style =" background-color : rgba(255, 165, 80, 0.5);font-weight: bold;" > {tempmax[4]}°C </td>
        <td style =" background-color : rgba(255, 165, 80, 0.5);font-weight: bold;" > {tempmax[5]}°C </td>
        <td style =" background-color : rgba(255, 165, 80, 0.5);font-weight: bold;" > {tempmax[6]}°C </td>
    </tr>
    <tr > 
        <td>  Temp Min (°C) </td>
        <td style =" background-color : rgba(144, 238, 144, 0.5);font-weight: bold;" > {tempmin[0]}°C </td>
        <td style =" background-color : rgba(144, 238, 144, 0.5);font-weight: bold;" > {tempmin[1]}°C </td>
        <td style =" background-color : rgba(144, 238, 144, 0.5);font-weight: bold;"> {tempmin[2]}°C </td>
        <td style =" background-color : rgba(144, 238, 144, 0.5);font-weight: bold;" > {tempmin[3]}°C </td>
        <td style =" background-color : rgba(144, 238, 144, 0.5);font-weight: bold;" > {tempmin[4]}°C </td>
        <td style =" background-color : rgba(144, 238, 144, 0.5);font-weight: bold;" > {tempmin[5]}°C </td>
        <td style =" background-color : rgba(144, 238, 144, 0.5);font-weight: bold;" > {tempmin[6]}°C </td>
    </tr>
    <tr> 
        <td> Humidity </td>
        <td> {meanhumidity[0]} % </td>
        <td> {meanhumidity[1]} % </td>
        <td> {meanhumidity[2]} % </td>
        <td> {meanhumidity[3]} % </td>
        <td> {meanhumidity[4]} % </td>
        <td> {meanhumidity[5]} % </td>
        <td> {meanhumidity[6]} % </td>
    </tr>
    <tr> 
        <td> Wind Speed Max  </td>
        <td> {int(wind[0])} km/h </td>
        <td> {int(wind[1])} km/h </td>
        <td> {int(wind[2])} km/h </td>
        <td> {int(wind[3])} km/h </td>
        <td> {int(wind[4])} km/h </td>
        <td> {int(wind[5])} km/h </td>
        <td> {int(wind[6])} km/h </td>
    </tr>
    <tr> 
        <td style="border-bottom-left-radius : 20px 20px"> Precipitation </td>
        <td> {iconrain(0)} {precipitation[0]} mm </td>
        <td> {iconrain(1)} {precipitation [1]} mm </td>
        <td> {iconrain(2)} {precipitation[2]} mm </td>
        <td> {iconrain(3)} {precipitation[3]} mm </td>
        <td> {iconrain(4)} {precipitation[4]} mm </td>
        <td> {iconrain(5)} {precipitation[5]} mm </td>
        <td style="border-bottom-right-radius : 20px 20px"> {iconrain(6)} {precipitationd} mm </td>
    </tr>
    </tbody>

</table>
"""
HTML(res)
Days Tuesday
29-7-2025
Wednesday
30-7-2025
Today
31-7-2025
Friday
1-8-2025
Saturday
2-8-2025
Sunday
3-8-2025
Monday
4-8-2025
Temp Max (°C) 31.1°C 30.9°C 31.2°C 33.0°C 31.0°C 33.2°C 33.8°C
Temp Min (°C) 20.4°C 20.7°C 20.5°C 22.8°C 22.1°C 21.1°C 20.6°C
Humidity 31.0 % 36.0 % 40.0 % 36.0 % 33.0 % 25.0 % 26.0 %
Wind Speed Max 18 km/h 19 km/h 18 km/h 20 km/h 22 km/h 24 km/h 20 km/h
Precipitation 0.0 mm 0.0 mm 0.0 mm 0.0 mm 0.0 mm 0.0 mm 0.0 mm