ChatGPT has changed the way we relate them to artificial intelligence. It is a chat that we can ask anything that through a written language offers us an answer. In this article we will explore some of the possibilities offered by ChatGPT to work with climate data.
This article will discuss how to get climatic data using ChatGPT as the code provider and the OpenWeatherMap API as the data source.
Introduction
ChatGPT everyone is talking about it, and sometimes it is said that its use will take with it thousands of jobs. Even without knowing the future, always in the history of humanity the great technological advances have been accompanied by black clouds. The work for people didn’t end when the sewing machine or motor machines came along. By definition, artificial intelligence is based on the fact that its development is to help people and that is what we have to keep in mind. Therefore, the world is going to adapt to this technology, as it has done before.
Escribir código de forma rápida en ChatGPT
After working on ChatGPT you realize that it will not take away work, it will improve what you do. When it comes to programming, it is a tool that will solve many problems. We follow this example developed by me in which I ask ChatGPT to help me work with weather data and we have this conversation:
you can explain how to do in Python to be able to work with functional data of the climate of a region
If you're interested in getting climate data using the 'pyowm' library and OpenWeatherMap API, here's the corrected code: ```python import pyowm def obtener_datos_climaticos(ciudad): try: owm = pyowm.OWM('TU_CLAVE_DE_API') observacion = owm.weather_manager().weather_at_place(ciudad) clima = observacion.weather ubicacion = observacion.location.name temperatura = clima.temperature('celsius')["temp"] humedad = clima.humidity viento = clima.wind()["speed"] estado_cielo = clima.status return { 'ubicacion': ubicacion, 'temperatura': temperatura, 'humedad': humedad, 'viento': viento, 'estado_cielo': estado_cielo } except pyowm.exceptions.api_response_error.NotFoundError: return None ciudad = 'Nombre_de_la_ciudad, Nombre_del_pais' datos_climaticos = obtener_datos_climaticos(ciudad) if datos_climaticos: print('Datos climáticos para', datos_climaticos['ubicacion']) print('Temperatura:', datos_climaticos['temperatura'], '°C') print('Humedad:', datos_climaticos['humedad'], '%') print('Viento:', datos_climaticos['viento'], 'km/h') print('Estado del cielo:', datos_climaticos['estado_cielo']) else: print('No se encontraron datos climáticos para la ubicación especificada.') ``` Be sure to replace ''TU_CLAVE_DE_API'' with your own OpenWeatherMap API key. Also, change ''Nombre_de_la_ciudad, Nombre_del_pais'' to the location for which you want to get the weather data. Remember that this code assumes that you have the 'pyowm' library installed correctly. If you don't have it installed, you can run 'pip install pyowm' to install it. I hope this time the code works properly for you. If you have more questions or need more help, please let me know. I'm here to help you.
Improving coding for climate data
Coding, if you’re learning to code, will help you code faster. It will even write the code for you. You just have to tell him what you want and he facilitates it and if he gives you an error, he corrects it and tells you the reason. I ask the following question “If I wanted to see the data of a whole month of temperature in a city and create a graph with the 10 minute data as I could do in python?” and he answers me like this:
To visualize temperature data on a graph over a month in 10-minute intervals, you can use the 'matplotlib' library in Python. Here's an example of how you might do this: ```python import pyowm import matplotlib.pyplot as plt import matplotlib.dates as mdates from datetime import timedelta def obtener_datos_climaticos(ciudad, fecha_inicio, dias): try: owm = pyowm.OWM('TU_CLAVE_DE_API') observacion = owm.weather_manager().weather_at_place(ciudad) clima = observacion.weather fechas = [] temperaturas = [] fecha_actual = fecha_inicio fecha_fin = fecha_inicio + timedelta(days=dias) while fecha_actual <= fecha_fin: observacion = owm.weather_manager().weather_at_place(ciudad, interval='10') clima = observacion.weather fechas.append(fecha_actual) temperaturas.append(clima.temperature('celsius')["temp"]) fecha_actual += timedelta(minutes=10) return fechas, temperaturas ciudad = 'Nombre_de_la_ciudad, Nombre_del_pais' fecha_inicio = datetime(2023, 6, 1) dias = 30 fechas, temperaturas = obtener_datos_climaticos(ciudad, fecha_inicio, dias) # Configuración del gráfico plt.figure(figsize=(12, 6)) plt.plot(fechas, temperaturas) plt.title('Temperatura en {}'.format(ciudad)) plt.xlabel('Fecha y Hora') plt.ylabel('Temperatura (°C)') # Formato de las fechas en el eje x plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y %H:%M')) plt.gca().xaxis.set_major_locator(mdates.DayLocator()) # Rotación de las etiquetas de fechas plt.xticks(rotation=45) plt.tight_layout() plt.show() ``` Be sure to replace ''TU_CLAVE_DE_API'' with your own OpenWeatherMap API key. Also, change ''Nombre_de_la_ciudad, Nombre_del_pais'' to the location for which you want to get the weather data. Set 'fecha_inicio' as the start date of the month and 'days' as the number of days you want to get the data. This code will obtain the climate data of the specified city in 10-minute intervals throughout the month and graph them using 'matplotlib'. The x-axis of the graph will show dates and times, and the y-axis will show temperatures in °C. I hope this helps you create the graph with the temperature data over the course of a month. If you have any more questions, don't hesitate to ask them. Good luck!
The previous code must be filled with the API that allows you to obtain the data and the place (location) that you want to visualize. It gives an error and ChatGPT provides me with this corrected code:
I'm sorry for any additional errors you've encountered. There seems to be a problem with the version of the PyOWM library you are using. In newer versions of PyOWM, the 'interval' argument is not available in the 'weather_at_place()' method. To solve this, we can make some modifications to the code to get the climate data at 10-minute intervals using a different approximation. Instead of using the 'interval' argument, we can manually adjust the date and time in 10-minute increments. Here's the modified code: ```python import pyowm import matplotlib.pyplot as plt import matplotlib.dates as mdates from datetime import datetime, timedelta def obtener_datos_climaticos(ciudad, fecha_inicio, fecha_fin): try: owm = pyowm.OWM('TU_CLAVE_DE_API') fechas = [] temperaturas = [] fecha_actual = fecha_inicio while fecha_actual <= fecha_fin: observacion = owm.weather_manager().weather_at_place(ciudad) clima = observacion.weather fechas.append(fecha_actual) temperaturas.append(clima.temperature('celsius')["temp"]) fecha_actual += timedelta(minutes=10) return fechas, temperaturas except pyowm.exceptions.api_response_error.NotFoundError: return None ciudad = 'Oia, Spain' fecha_inicio = datetime(2023, 5, 1) fecha_fin = datetime(2023, 6, 1, 23, 59) fechas, temperaturas = obtener_datos_climaticos(ciudad, fecha_inicio, fecha_fin) if fechas is not None: # Configuración del gráfico plt.figure(figsize=(12, 6)) plt.plot(fechas, temperaturas) plt.title('Temperatura en {}'.format(ciudad)) plt.xlabel('Fecha y Hora') plt.ylabel('Temperatura (°C)') # Formato de las fechas en el eje x plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y %H:%M')) plt.gca().xaxis.set_major_locator(mdates.DayLocator()) # Rotación de las etiquetas de fechas plt.xticks(rotation=45) plt.tight_layout() plt.show() else: print('No se encontraron datos climáticos para la ubicación especificada.') ``` Remember to replace ''TU_CLAVE_DE_API'' with your own OpenWeatherMap API key and adjust the 'city' variable according to the desired location. I hope this modified code solves the problem and allows you to generate the graph with the temperature data throughout the specified month. If you have any more questions, don't hesitate to ask them. Good luck!
In the end the result was obtained from this code:
import pyowm def obtener_datos_climaticos(ciudad): try: owm = pyowm.OWM('YOUR-APY-KEY') observacion = owm.weather_manager().weather_at_place(ciudad) clima = observacion.weather ubicacion = observacion.location.name temperatura = clima.temperature('celsius')["temp"] humedad = clima.humidity viento = clima.wind()["speed"] estado_cielo = clima.status return { 'ubicacion': ubicacion, 'temperatura': temperatura, 'humedad': humedad, 'viento': viento, 'estado_cielo': estado_cielo } except pyowm.exceptions.api_response_error.NotFoundError: return None ciudad = 'Oia, Spain' datos_climaticos = obtener_datos_climaticos(ciudad) if datos_climaticos: print('Datos climáticos para', datos_climaticos['ubicacion']) print('Temperatura:', datos_climaticos['temperatura'], '°C') print('Humedad:', datos_climaticos['humedad'], '%') print('Viento:', datos_climaticos['viento'], 'km/h') print('Estado del cielo:', datos_climaticos['estado_cielo']) else: print('No se encontraron datos climáticos para la ubicación especificada.')
Y se obtuvo este resultado:
Climate data for Oiã Temperature: 29.9 °C Humidity: 45 % Wind: 3.34 km/h State of the sky: Clear
The power of prompts
Using ChatGPT is all about prompts, the power is in the prompts, the better the prompts the better the results you will get. For ChatGPT to help you create a code you have to give it precise instructions, and from its answers, ask again to get what you want. Google gives you page information that can help you find something you’re looking for, but it’s not going to help you create code and carve it until you get the result you want.
Also, you don’t have to know Python or another programming language, it just did it for you. And you only use an interpreter program of the language you are using to develop the result obtained.
Summary
ChatGPT will allow you to generate code that can help you solve problems you want to solve, it is therefore a guide for your work or study. If you want to learn Python it will guide you step by step on how to do it. In this article, OpenWeatherMap is used as a data source that provides us with an API (a gateway to obtain data) and ChatGPT provides us with the Python code to handle climate data that can be used for any locality that is in the OpenWeatherMap database.