search
HomeBackend DevelopmentPython TutorialGet and store time series data with Python

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.

Requirements

This 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

This tutorial also assumes that you have already created a Free Tier InfluxDB cloud account or are using InfluxDB OSS, and that you have also:

    Created the bucket. You can think of buckets as the highest level of data organization in a database or InfluxDB.
  • Token created.
Finally, this tutorial requires that you have already created an account with OpenWeatherMap and created a token.

Request weather data

First, we need to request data. We will use the requests library to return hourly weather data from a specified longitude and latitude via the OpenWeatherMap API.

# 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 into Pandas DataFrame

Next, convert the JSON data into Pandas DataFrame. We also convert the timestamp from a second-precision Unix timestamp to a datetime object. This conversion is done because the InfluxDB write method requires the timestamp to be in datetime object format. Next, we will use this method to write data to InfluxDB. We also removed columns that we didn't want written to InfluxDB.

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)

Writing Pandas DataFrame to InfluxDB

Now create an instance of the InfluxDB Python client library and write the DataFrame to InfluxDB. We specified the measurement name. Measurements contain data in buckets. You can think of it as the second-highest level structure in InfluxDB's data organization after buckets.

You can also use the data_frame__tag_columns parameter to specify which columns are converted to tags.

Since we did not specify any columns as labels, all of our columns will be converted into fields in InfluxDB. Tags are used to write metadata about your time series data, which can be used to query subsets of the data more efficiently. Fields are where you store the actual time series data in InfluxDB. This document (https://docs.influxdata.com/influxdb/cloud/reference/key-concepts/?utm_source=vendor&utm_medium=referral&utm_campaign=2022-07_spnsr-ctn_obtaining-storing-ts-pything_tns) goes into more detail about These data concepts.

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")

Full script

To review, you might as well take a look at the complete script. We take the following steps:

1. Import the library.

2. Collect the following:

    InfluxDB Bucket
  • InfluxDB Organization
  • InfluxDB Token
  • InfluxDB URL
  • OpenWeatherMap URL
  • OpenWeatherMap Token
3. Create the request.

4. Convert JSON response into Pandas DataFrame.

5. Delete any columns that you do not want to write to InfluxDB.

6. Convert timestamp column from Unix time to Pandas datetime object.

7. Create an instance for the InfluxDB Python Client library.

8. Write a DataFrame and specify the measurement name and timestamp column.

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")

Query data

Now that we have written the data to InfluxDB, we can use the InfluxDB UI to query the data. Navigate to Data Explorer (from the left navigation bar). Using Query Builder, select the data you want to visualize and the range you want to visualize, and click Submit.

Get and store time series data with Python

Figure 1. Default materialized view of weather data. InfluxDB automatically aggregates time series data so new users don't accidentally query too much data and cause timeouts

Pro Tip: When you query data using the query builder, InfluxDB automatically downsamples the data. To query raw data, navigate to the Script Editor to view the underlying Flux query. Flux is a native query and scripting language for InfluxDB that can be used to analyze and create predictions using your time series data. Use the aggregateWindow() function to uncomment or delete rows to see the original data.

Get and store time series data with Python

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!

Statement
This article is reproduced at:51CTO.COM. If there is any infringement, please contact admin@php.cn delete
Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),