Example #1
0
def _weather_data_extraction(lat, lon):
    start = datetime(2015, 1, 1)
    end = datetime(2021, 1, 16)

    stations = Stations()
    stations = stations.nearby(lat, lon)
    stations = stations.inventory('daily', (start, end))
    station = stations.fetch(1)

    data = Daily(station, start, end)
    data = data.fetch()

    return data
Example #2
0
 def get_historical_data(self):
     """
     returns: Dataframe of historical average temperature for a given city
              within the specified time period
     """
     lat, lon = self.get_lat_and_lon()
     city = Point(lat, lon)
     data = Daily(city, self.start_date, self.end_date)
     data = data.fetch()
     data = data.filter(['tavg'])  # select average temperature column
     data = data.fillna(method='ffill')  # fill missing values
     # get a specific day
     #day = data.iloc[lambda x: x.index  == '2014-06-23']
     return data
Example #3
0
from datetime import datetime
from meteostat import Point, Daily
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib as mpl
import pandas as pd

start = datetime(2021, 1, 1)
end = datetime(2021, 12, 31)
oslo = Point(59.9139, 10.7522)
od = Daily(oslo, start, end)
od = od.fetch()
print(od.isnull().sum())
df = od.drop(['snow', 'wdir', 'wspd', 'wpgt', 'pres', 'tsun'], axis=1)
df = df.dropna()
print(df)
print(df.isna().sum())
corr = df.corr()
print(corr)
sns.heatmap(corr, cmap="Blues", annot=True)

if not od.empty:
    exit()
Example #4
0
"""
Example: Comparing multiple weather stations

Meteorological data provided by Meteostat (https://dev.meteostat.net)
under the terms of the Creative Commons Attribution-NonCommercial
4.0 International Public License.

The code is licensed under the MIT license.
"""

from datetime import datetime
import matplotlib.pyplot as plt
from meteostat import Daily

# Time period
start = datetime(2019, 1, 1)
end = datetime(2019, 12, 31)

# Get daily data
data = Daily(['71624', '72295', '68816', '94767'], start, end)
data = data.fetch()

# Plot chart
data.unstack('station')['tavg'].plot(
    legend=True,
    ylabel='Avg. Daily Temperature °C',
    title='Average Temperature Report for 2019')
plt.show()
Example #5
0
def stations_daily():
    """
    Return daily station data in JSON format
    """

    # Get query parameters
    args = utils.get_parameters(parameters)

    # Check if required parameters are set
    if args['station'] and len(args['start']) == 10 and len(args['end']) == 10:

        try:

            # Convert start & end date strings to datetime
            start = datetime.strptime(args['start'], '%Y-%m-%d')
            end = datetime.strptime(f'{args["end"]} 23:59:59',
                                    '%Y-%m-%d %H:%M:%S')

            # Get number of days between start and end date
            date_diff = (end - start).days

            # Check date range
            if date_diff < 0 or date_diff > max_days:
                # Bad request
                abort(400)

            # Caching
            now_diff = (datetime.now() - end).days

            if now_diff < 30:
                cache_time = 60 * 60 * 24
            else:
                cache_time = 60 * 60 * 24 * 3

            Daily.max_age = cache_time

            # Get data
            data = Daily(args['station'], start, end, model=args['model'])

            # Check if any data
            if data.count() > 0:

                # Normalize data
                data = data.normalize()

                # Aggregate
                if args['freq']:
                    data = data.aggregate(args['freq'])

                # Unit conversion
                if args['units'] == 'imperial':
                    data = data.convert(units.imperial)
                elif args['units'] == 'scientific':
                    data = data.convert(units.scientific)

                # Fetch DataFrame
                data = data.fetch()

                # Convert to integer
                data['tsun'] = data['tsun'].astype('Int64')

                # DateTime Index to String
                data.index = data.index.strftime('%Y-%m-%d')
                data.index.rename('date', inplace=True)
                data = data.reset_index().to_json(orient="records")

            else:

                # No data
                data = '[]'

            # Inject meta data
            meta = {}
            meta['generated'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

            # Generate output string
            output = f'''{{"meta":{json.dumps(meta)},"data":{data}}}'''

            # Return
            return utils.send_response(output, cache_time)

        except BaseException:

            # Bad request
            abort(400)

    else:

        # Bad request
        abort(400)
Example #6
0
def get_raw_data(station_id, start=start, end=end):
    data_daily = Daily([station_id], start=start, end=end)
    return data_daily.fetch()