Get and store time series data with Python
##Translator| Bugatti
Reviewer| Sun Shujuan
This tutorial will introduce how to Use Python to get time series data from the OpenWeatherMap API and convert it into a Pandas DataFrame. Next, we will use the InfluxDB Python Client to write this data to the time series data platform InfluxDB. We will convert the JSON response from the API call into a Pandas DataFrame as this is the easiest way to write data to InfluxDB. Since InfluxDB is a purpose-built database, our writes to InfluxDB are designed to meet the high requirements in terms of ingestion of time series data. RequirementsThis tutorial is completed on a macOS system that has Python 3 installed via Homebrew. It is recommended to install additional tools such as virtualenv, pyenv or conda-env to simplify the installation of Python and Client. The full requirements are here:txt influxdb-client=1.30.0 pandas=1.4.3 requests>=2.27.1
- Created the bucket. You can think of buckets as the highest level of data organization in a database or InfluxDB. Token created.
# Get time series data from OpenWeatherMap API params = {'lat':openWeatherMap_lat, 'lon':openWeatherMap_lon, 'exclude': "minutely,daily", 'appid':openWeatherMap_token} r = requests.get(openWeather_url, params = params).json() hourly = r['hourly']
python # Convert data to Pandas DataFrame and convert timestamp to datetime object df = pd.json_normalize(hourly) df = df.drop(columns=['weather', 'pop']) df['dt'] = pd.to_datetime(df['dt'], unit='s') print(df.head)
on # Write data to InfluxDB with InfluxDBClient(url=url, token=token, org=org) as client: df = df client.write_api(write_options=SYNCHRONOUS).write(bucket=bucket,record=df, data_frame_measurement_name="weather", data_frame_timestamp_column="dt")
- InfluxDB BucketInfluxDB OrganizationInfluxDB TokenInfluxDB URLOpenWeatherMap URLOpenWeatherMap Token
python import requests import influxdb_client import pandas as pd from influxdb_client import InfluxDBClient from influxdb_client.client.write_api import SYNCHRONOUS bucket = "OpenWeather" org = "" # or email you used to create your Free Tier InfluxDB Cloud account token = " url = "" # for example, https://us-west-2-1.aws.cloud2.influxdata.com/ openWeatherMap_token = "" openWeatherMap_lat = "33.44" openWeatherMap_lon = "-94.04" openWeather_url = "https://api.openweathermap.org/data/2.5/onecall" # Get time series data from OpenWeatherMap API params = {'lat':openWeatherMap_lat, 'lon':openWeatherMap_lon, 'exclude': "minutely,daily", 'appid':openWeatherMap_token} r = requests.get(openWeather_url, params = params).json() hourly = r['hourly'] # Convert data to Pandas DataFrame and convert timestamp to datetime object df = pd.json_normalize(hourly) df = df.drop(columns=['weather', 'pop']) df['dt'] = pd.to_datetime(df['dt'], unit='s') print(df.head) # Write data to InfluxDB with InfluxDBClient(url=url, token=token, org=org) as client: df = df client.write_api(write_options=SYNCHRONOUS).write(bucket=bucket,record=df, data_frame_measurement_name="weather", data_frame_timestamp_column="dt")
Figure 2. Navigate to the Script Editor and uncomment or delete the aggregateWindow() function to view the raw weather data
Conclusion
Hopefully this article helped you get the most out of InfluxDB Python Client library, obtains time series data and stores it in InfluxDB. If you want to learn more about using the Python Client library to query data from InfluxDB, I recommend you take a look at this article (https://thenewstack.io/getting-started-with-python-and-influxdb/). It's also worth mentioning that you can use Flux to get data from the OpenWeatherMap API and store it into InfluxDB. If you use InfluxDB Cloud, this means that the Flux script will be hosted and executed periodically, so you can get a reliable stream of weather data fed into the instance. To learn more about how to use Flux to obtain weather data on a user-defined schedule, please read this article (https://www.influxdata.com/blog/tldr-influxdb-tech-tips-handling-json-objects-mapping- arrays/?utm_source=vendor&utm_medium=referral&utm_campaign=2022-07_spnsr-ctn_obtaining-storing-ts-pything_tns).
The above is the detailed content of Get and store time series data with Python. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".
