示例#1
0
    def test_point(self):
        """
        Test: Point Data
        """

        # Create Point for Vancouver, BC
        point = Point(49.2497, -123.1193, 70)

        # Get count of weather stations
        stations = point.get_stations('daily', datetime(2020, 1, 1),
                                      datetime(2020, 1, 31))

        # Check if three stations are returned
        self.assertEqual(
            len(stations.index), 4,
            f'{len(stations.index)} weather stations returned, should be 4')
示例#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
示例#3
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
示例#4
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()
示例#5
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
示例#6
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)
示例#7
0
def point_monthly():
    """
    Return monthly 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:
                # Bad request
                abort(400)

            # Caching
            Monthly.max_age = 60 * 60 * 24 * 7

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

            # Get data
            data = Monthly(location, 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')
            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)
示例#8
0
"""
Example: Daily point 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
import matplotlib.pyplot as plt
from meteostat import Point, Daily

# Set time period
start = datetime(2018, 1, 1)
end = datetime(2018, 12, 31)

# Create Point for Vancouver, BC
vancouver = Point(49.2497, -123.1193, 70)

# Get daily data for 2018
data = Daily(vancouver, start, end)
data = data.fetch()

# Plot line chart including average, minimum and maximum temperature
data.plot(y=['tavg', 'tmin', 'tmax'])
plt.show()
示例#9
0
from datetime import datetime
import pandas as pd
from meteostat import Point, Daily

start = datetime(2018, 1, 1)
end = datetime(2021, 3, 8)

YT = Point(37.251494, 127.071288)

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

df = pd.DataFrame(data)
df.to_csv('weather.csv', index=True)

test = 1