Exemple #1
0
        def meteostat(lat_degr,long_degr,alt_avrg,start_time,end_time):
            #Retrieve nearest weather station
            stations = Stations()
            stations = stations.nearby(lat_degr, long_degr)
            station = stations.fetch(1)

            #Use Point to agregate nearby weather stations data for better accuracy
            weather_point = Point(lat_degr, long_degr,alt_avrg)
            weather_data = Hourly(weather_point, start_time - timedelta(0,7200), end_time + timedelta(0,7200))
            weather_data = weather_data.fetch()
            #Use weather data from nearest station if Point returns an empty dataset
            if weather_data.empty:
                weather_data = Hourly(station, start_time - timedelta(0,7200), end_time + timedelta(0,7200))
                weather_data = weather_data.fetch()
            return weather_data
Exemple #2
0
def fetch(
        start=datetime(2020, 1, 1),
        end=datetime.now(),
        lat=33.5020,  # Closest to UAB
        lon=-86.8064):
    start += timedelta(hours=6)  # UTC offset
    end += timedelta(hours=6)
    end.replace(microsecond=0, second=0)
    stations = Stations(lat=lat, lon=lon)
    station = stations.fetch(1)
    data = Hourly(station, start, end)
    data = data.normalize()
    data = data.interpolate()
    df = data.fetch()
    out = {}
    last_row = None
    for row in df.itertuples():
        if last_row:
            out.update(interpolate_minutes(last_row, row))
        last_row = row
    current_time = last_row.time - timedelta(hours=6)
    while current_time <= end - timedelta(hours=6):
        out[create_datetime_ID(current_time)] = {
            "time": current_time,
            "temp": last_row.temp
        }
        current_time += timedelta(minutes=1)
    return out
Exemple #3
0
def get_weather(station: str, start: datetime, end: datetime) -> dict:
    # Get hourly data
    hourly_obs = Hourly(station, start, end)
    df = hourly_obs.fetch()
    return {
        "rain": df["prcp"].fillna(0).sum(),
        "temperature": df["temp"].mean(),
        "wind_speed": df["wspd"].mean(),
    }
Exemple #4
0
    def test_coverage(self):

        # Get data for some day at Frankfurt Airport
        data = Hourly(['10637'], start = datetime(2018, 1, 1), end = datetime(2018, 1, 1, 23, 59))
        coverage = data.normalize().coverage()

        # Check if coverage is 100%
        self.assertEqual(
            coverage,
            1,
            'Normalized hourly data returns coverage of ' + str(coverage) + ', should be 1'
        )
Exemple #5
0
    def test_aggregate(self):

        # Get data for some days at Frankfurt Airport
        data = Hourly(['10637'], start = datetime(2018, 1, 1), end = datetime(2018, 1, 3, 23, 59))
        count = data.normalize().aggregate(freq = '1D').count()

        # Check if count matches 3
        self.assertEqual(
            count,
            3,
            'Aggregated hourly data returns count of ' + str(count) + ', should be 3'
        )
Exemple #6
0
    def test_normalize(self):

        # Get data for some day at Frankfurt Airport
        data = Hourly(['10637'], start = datetime(2018, 1, 1), end = datetime(2018, 1, 1, 23, 59))
        count = data.normalize().count()

        # Check if count matches 24
        self.assertEqual(
            count,
            24,
            'Normalized hourly data returns count of ' + str(count) + ', should be 24'
        )
Exemple #7
0
"""
Example: Simple chart

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 Stations, Hourly

# Get a weather station
stations = Stations()
stations = stations.nearby(50, 8)
station = stations.fetch(1)

# Time period
start = datetime(2017, 1, 1)
end = datetime(2017, 1, 1, 23, 59)

# Get hourly data
data = Hourly(station, start, end)
data = data.fetch()

# Plot chart
data.plot(y='temp')
plt.show()
Exemple #8
0
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
from meteostat import Stations, Hourly
from meteostat.units import fahrenheit, direction, condition

# Time period
start = datetime(2018, 1, 1)
end = datetime(2018, 1, 1, 23, 59)

# Get nearby weather station
stations = Stations()
stations = stations.nearby(50, 8)
station = stations.fetch(1)

# Get hourly data
data = Hourly(station, start, end, timezone='Europe/Berlin')

# Convert data units
data = data.convert({'temp': fahrenheit, 'wdir': direction, 'coco': condition})

# Print to console
data = data.fetch()
print(data)
Exemple #9
0
def get_weather(road):

    #url='http://pro.openweathermap.org/data/2.5/weather?q=Birmingham,uk&APPID=b68960a402d40a497b69695725ad73af'

    # Create Point for Birmingham
    #Birmingham = Point(52.49, -1.86, 140)
    #Bradford = Point(53.79, -1.75, 168.78)
    #Leeds= Point(53.801277, -1.548567, 340)

    #print('City : ',City)
    month = datetime.today().month
    day = datetime.today().day
    year = datetime.today().year
    hour = datetime.today().hour
    #print(year, month, day, hour, City)
    start = datetime(year, month, day, hour, 0)
    end = datetime(year, month, day, hour, 59)
    #print(hour)
    if road == 'M606':
        #City = Point(53.79, -1.75, 168.78)
        data = Hourly(Point(53.79, -1.75, 168.78), start, end)
        #City='Bradford'
    elif road == 'M621':
        #City='Leeds'
        City = Point(53.801277, -1.548567, 340)
        data = Hourly(Point(53.801277, -1.548567, 340), start, end)
    elif road == 'A38(M)':
        #City='Birmingham'
        City = Point(52.49, -1.86, 140)
        data = Hourly(Point(52.49, -1.86, 140), start, end)
    #data = Hourly(City, start, end)
    weather_df = data.fetch()
    print(start)
    print(weather_df)
    coco = list(weather_df['coco'])
    #print(coco[0])
    #str1=str(round(coco[0]))
    #print(str1)
    #print(weather[coco])

    weather = {
        '1': 'Clear',
        '2': 'Fair',
        '3': 'Cloudy',
        '4': 'Overcast',
        '5': 'Fog',
        '6': 'Freezing Fog',
        '7': 'Light Rain',
        '8': 'Rain',
        '9': 'Heavy Rain',
        '10': 'Freezing Rain',
        '11': 'Heavy Freezing Rain',
        '12': 'Sleet',
        '13': 'Heavy Sleet',
        '14': 'Light Snowfall',
        '15': 'Snowfall',
        '16': 'Heavy Snowfall',
        '17': 'Rain Shower',
        '18': 'Heavy Rain Shower',
        '19': 'Sleet Shower',
        '20': 'Heavy Sleet Shower',
        '21': 'Snow Shower',
        '22': 'Heavy Snow Shower',
        '23': 'Lightning',
        '24': 'Hail',
        '25': 'Thunderstorm',
        '26': 'Heavy Thunderstorm',
        '27': 'Storm'
    }

    weather_df = weather_df.reset_index()
    #print(weather[str1])

    return coco
Exemple #10
0
under the terms of the Creative Commons Attribution-NonCommercial
4.0 International Public License.

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

if __name__ == '__main__':

    from timeit import default_timer as timer

    # Get start time
    s = timer()

    # Run script
    from datetime import datetime
    from meteostat import Hourly

    Hourly.cores = 12

    start = datetime(1960, 1, 1)
    end = datetime(2021, 1, 1, 23, 59)

    data = Hourly('10637', start, end, timezone='Europe/Berlin')
    data = data.fetch()

    # Get end time
    e = timer()

    # Print performance
    print(e - s)
Exemple #11
0
"""
Example: Hourly data access

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
from meteostat import Point, Hourly

# Time period
start = datetime(2021, 1, 1)
end = datetime(2021, 1, 1, 23, 59)

# The point
point = Point(50.3167, 8.5, 320)

# Get hourly data
data = Hourly(point, start, end, timezone='Europe/Berlin')

# Print to console
data = data.fetch()
print(data)
Exemple #12
0
def point_hourly():
    """
    Return hourly point data in JSON format
    """

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

    # Check if required parameters are set
    if args['lat'] and args['lon'] 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 < 3:
                cache_time = 60 * 60
            elif now_diff < 30:
                cache_time = 60 * 60 * 24
            else:
                cache_time = 60 * 60 * 24 * 3

            Hourly.max_age = cache_time

            # Create a point
            location = Point(args['lat'], args['lon'], args['alt'])

            # Get data
            data = Hourly(location,
                          start,
                          end,
                          timezone=args['tz'],
                          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')
                data['coco'] = data['coco'].astype('Int64')

                # DateTime Index to String
                data.index = data.index.strftime('%Y-%m-%d %H:%M:%S')
                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')
            meta['stations'] = location.stations.to_list()

            # 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)
from meteostat import Stations, Hourly
from datetime import datetime

# Hourly
stations = Stations(wmo='10637')
station = stations.fetch(1)

data = Hourly(station,
              start=datetime(2020, 1, 1),
              end=datetime(2020, 1, 1, 23, 59)).aggregate(freq='1D')
print(data.fetch())
"""
Example: Aggregation

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
from meteostat import Hourly

# Time period
start = datetime(2018, 1, 1)
end = datetime(2018, 1, 1, 23, 59)

# Get hourly data & aggregate daily
data = Hourly('10637', start, end)
data = data.aggregate('1D')
data = data.fetch()

# Print
print(data)
Exemple #15
0
from meteostat import Stations, Hourly
from datetime import datetime
import matplotlib.pyplot as plt

# Hourly
stations = Stations(lat = 50, lon = 8)
station = stations.fetch(1)

data = Hourly(station, start = datetime(2010, 1, 1), end = datetime(2020, 1, 1, 23, 59))
data = data.fetch()

data.plot(x = 'time', y = ['temp'], kind = 'line')
plt.show()
Exemple #16
0
"""
Example: Interpolation

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 Hourly

# Time period
start = datetime(2018, 8, 1)
end = datetime(2018, 8, 4, 23, 59)

# Get hourly data
data = Hourly('10730', start, end)
data = data.normalize()
data = data.interpolate(6)
data = data.fetch()

# Plot chart
data.plot(y='temp')
plt.show()
from meteostat import Stations, Hourly
from datetime import datetime
import matplotlib.pyplot as plt

# Hourly
station = ['10637']

data = Hourly(station,
              start=datetime(2020, 8, 1),
              end=datetime(2020, 8, 4, 23, 59))
data = data.normalize()
data = data.interpolate().fetch()
data.plot(x='time', y=['temp'], kind='line')
plt.show()