##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.1This 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.
# 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 DataFrameNext, 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 InfluxDBNow 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 scriptTo 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
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 dataNow 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.
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!

Pythonisbothcompiledandinterpreted.WhenyourunaPythonscript,itisfirstcompiledintobytecode,whichisthenexecutedbythePythonVirtualMachine(PVM).Thishybridapproachallowsforplatform-independentcodebutcanbeslowerthannativemachinecodeexecution.

Python is not strictly line-by-line execution, but is optimized and conditional execution based on the interpreter mechanism. The interpreter converts the code to bytecode, executed by the PVM, and may precompile constant expressions or optimize loops. Understanding these mechanisms helps optimize code and improve efficiency.

There are many methods to connect two lists in Python: 1. Use operators, which are simple but inefficient in large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use the = operator, which is both efficient and readable; 4. Use itertools.chain function, which is memory efficient but requires additional import; 5. Use list parsing, which is elegant but may be too complex. The selection method should be based on the code context and requirements.

There are many ways to merge Python lists: 1. Use operators, which are simple but not memory efficient for large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use itertools.chain, which is suitable for large data sets; 4. Use * operator, merge small to medium-sized lists in one line of code; 5. Use numpy.concatenate, which is suitable for large data sets and scenarios with high performance requirements; 6. Use append method, which is suitable for small lists but is inefficient. When selecting a method, you need to consider the list size and application scenarios.

Compiledlanguagesofferspeedandsecurity,whileinterpretedlanguagesprovideeaseofuseandportability.1)CompiledlanguageslikeC arefasterandsecurebuthavelongerdevelopmentcyclesandplatformdependency.2)InterpretedlanguageslikePythonareeasiertouseandmoreportab

In Python, a for loop is used to traverse iterable objects, and a while loop is used to perform operations repeatedly when the condition is satisfied. 1) For loop example: traverse the list and print the elements. 2) While loop example: guess the number game until you guess it right. Mastering cycle principles and optimization techniques can improve code efficiency and reliability.

To concatenate a list into a string, using the join() method in Python is the best choice. 1) Use the join() method to concatenate the list elements into a string, such as ''.join(my_list). 2) For a list containing numbers, convert map(str, numbers) into a string before concatenating. 3) You can use generator expressions for complex formatting, such as ','.join(f'({fruit})'forfruitinfruits). 4) When processing mixed data types, use map(str, mixed_list) to ensure that all elements can be converted into strings. 5) For large lists, use ''.join(large_li

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.


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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
