コード例 #1
0
def detect_timezone(config):
    try:
        tf = TimezoneFinder()
        timezone_str = tf.timezone_at(lng=config.lat_lon_coord[1],
                                      lat=config.lat_lon_coord[0])
        if (timezone_str == None):
            timezone_str = tf.certain_timezone_at(lng=config.lat_lon_coord[1],
                                                  lat=config.lat_lon_coord[0])
        elif (timezone_str == None):
            timezone_str = tf.closest_timezone_at(lng=config.lat_lon_coord[1],
                                                  lat=config.lat_lon_coord[0])

        if (timezone_str != None):
            config.timezone = timezone(timezone_str)
            config.tz_label = config.timezone
            config.valid = True
            config.logger.console_log(config, "control", "info",
                                      "timezone detected >> " + timezone_str,
                                      False)
        else:
            if (config.mode == "batch"):
                config.logger.console_log(
                    config, "control", "error",
                    "timezone could not be auto-detected, given lat long may be offshore",
                    True)  #exit on auto detect failure
            else:
                config.logger.console_log(
                    config, "control", "error",
                    "timezone could not be auto-detected, given lat long may be offshore",
                    False)
    except:
        config.logger.console_log(config, "control", "error",
                                  "Timezone detect encoutered an error", False)
    return config
コード例 #2
0
 def get_site_tz_info(self, site):
     tf = TimezoneFinder()
     timezone = tf.certain_timezone_at(lng=site.longitude,
                                       lat=site.latitude)
     return json.dumps({
         "site_timezone": timezone,
         "tz_list": pytz.all_timezones
     })
コード例 #3
0
def get_offset(*, lat, lon):
    """Get UTC time zone delta/offset in hours"""
    tf = TimezoneFinder()
    today = datetime.now()
    tz_target = timezone(tf.certain_timezone_at(lng=lon, lat=lat))
    # ATTENTION: tz_target could be None! handle error case
    today_target = tz_target.localize(today)
    today_utc = utc.localize(today)
    hour_offset = (today_utc - today_target).total_seconds() / 3600
    return hour_offset
コード例 #4
0
ファイル: plan.py プロジェクト: franpoz/SHERLOCK
def get_offset(lat, lng, datetime):
    """
    returns a location's time zone offset from UTC in minutes.
    """
    tf = TimezoneFinder()
    tz_target = timezone(tf.certain_timezone_at(lng=lng, lat=lat))
    if tz_target is None:
        return None
    today_target = tz_target.localize(datetime)
    today_utc = utc.localize(datetime)
    return (today_utc - today_target).total_seconds() / 3600
コード例 #5
0
def location(update, context):
    tf = TimezoneFinder()
    longitude = update.message.location['longitude']
    latitude = update.message.location['latitude']
    local_tz = datetime.now(
        pytz.timezone(tf.certain_timezone_at(lng=longitude,
                                             lat=latitude))).strftime('%Z%z')
    tz_hours = int(local_tz[-5:]) // 100
    tz_minutes = int(local_tz[-5:]) % 100
    context.chat_data['local_tz'] = {'hours': tz_hours, 'minutes': tz_minutes}
    update.message.reply_text("Локация сохранена")
コード例 #6
0
def location(update, context):
    tf = TimezoneFinder()
    time_now = datetime.now()
    longitude = update.message.location['longitude']
    latitude = update.message.location['latitude']
    a = datetime.now(pytz.timezone(tf.certain_timezone_at(lng=longitude, lat=latitude))).strftime('%Z%z')
    b = pytz.timezone(tf.certain_timezone_at(lng=longitude, lat=latitude))
    print(b)
    tzzz_hours = int(a[-5:]) // 100
    tzzz_minutes = int(a[-5:]) % 100
    # due = datetime(time_now.year, time_now.month, time_now.day, 1, 2,
    #                tzinfo=timezone(timedelta(hours=int(a[-5:]) / 100)))
    # print(due)
    # task_time = datetime(time_now.year, time_now.month, time_now.day, int(1),
    #                      int(1), tzinfo=timezone(timedelta(hours=tzzz)))
    # print(task_time)
    task_time = datetime(time_now.year, time_now.month, time_now.day, int(1),
                         int(1), tzinfo=timezone(timedelta(hours=tzzz_hours, minutes=tzzz_minutes))).astimezone(utc)
    print(task_time)
    context.chat_data['local_tz'] = {'hours': tzzz_hours, 'minutes': tzzz_minutes}
    print(context.chat_data)
コード例 #7
0
def offset(lat,lon):
    # libraries
    import pytz
    import time; import pandas as pd; import numpy as np; import dateutil.parser as dparser
    from timezonefinder import TimezoneFinder; from pytz import timezone; from datetime import datetime,date, timedelta
    tf = TimezoneFinder(in_memory=True)
    utc = pytz.utc
    #returns a location's time zone offset from UTC in minutes.
    today = datetime.now()
    tz_target = timezone(tf.certain_timezone_at(lat=lat, lng=lon))
    # ATTENTION: tz_target could be None! handle error case
    today_target = tz_target.localize(today)
    today_utc = utc.localize(today)
    return (today_utc - today_target).total_seconds() / 3600
コード例 #8
0
def get_local_time(utc_time, lat, lon):
    from_zone = tz.gettz('UTC')
    tf = TimezoneFinder()
    to_zone = tz.gettz(tf.certain_timezone_at(lng=float(lon), lat=float(lat)))
    print(to_zone)
    your_zone = tz.tzlocal()
    print(utc_time)
    try:
        utc = datetime.datetime.strptime(
            utc_time, '%Y-%m-%d %H:%M:%S.%f')  # set the UTC time
    except:  # sometimes the time isn't specific enoug and doesn't have a .%f
        utc = datetime.datetime.strptime(utc_time, '%Y-%m-%d %H:%M:%S')
    utc = utc.replace(tzinfo=from_zone)  # set the utc timezone
    local_time = utc.astimezone(to_zone)
    your_time = utc.astimezone(your_zone)
    return local_time, your_time
コード例 #9
0
def utc_offset(location_valid, lat, lng):
    """
    Returns a location's UTC offset in hours.
    Arguments:
    location_valid -- whether lat and lng have been determined by get_lat_long
    lat -- location's latitude
    lng -- location's longitude
    """
    if not location_valid:
        return 0
    today = datetime.now()
    tf = TimezoneFinder(in_memory=True)
    tz_target = timezone(tf.certain_timezone_at(lng=lng, lat=lat))
    if tz_target is None:
        return 0
    today_target = tz_target.localize(today)
    today_utc = utc.localize(today)
    return (today_utc - today_target).total_seconds() / 3600
コード例 #10
0
def convert_timestamp_with_coordinates(lat, lng, timestamp):
    """
    default regard timestamp as UTC timezone and convert it to its local timezone which get from coords (lat and lng)
    return string format dd/mm/yyyy hh:mm Z +/-hhmm
    """
    from datetime import datetime
    from timezonefinder import TimezoneFinder
    from pytz import timezone

    tf = TimezoneFinder()

    # From the lat/long, get the tz-database-style time zone name (e.g. 'America/Vancouver') or None
    timezone_str = tf.certain_timezone_at(lat=lat, lng=lng)
    timezone = timezone(timezone_str)

    fmt = '%d/%m/%Y %H:%M %Z %z'

    time = datetime.fromtimestamp(timestamp).astimezone(timezone).strftime(fmt)

    return time
コード例 #11
0
    async def get_timezone(self, ctx, ip):
        """
        returns your timezone relative to UTC
        """
        if ctx.author.id not in self.tz:
            # Get GMT offset and store the offset in a json object
            async with aiohttp.ClientSession() as session:
                async with session.get(
                        "https://api.radar.io/v1/geocode/ip",
                        params={"ip": ip},
                        headers={
                            "Authorization": os.environ.get("RADAR_TOKEN")
                        },
                ) as r:
                    r = await r.json()
                    lat = r["address"]["latitude"]
                    lng = r["address"]["longitude"]

                    today = datetime.now()
                    tf = TimezoneFinder()
                    tz_target = timezone(
                        tf.certain_timezone_at(lng=lng, lat=lat))
                    today_target = tz_target.localize(today)
                    today_utc = utc.localize(today)
                    utc_offset = (today_utc -
                                  today_target).total_seconds() / 3600
                    await ctx.author.send(
                        f"You are: {utc_offset} hours from UTC")
            # Store UTC offset
            self.tz[ctx.author.id] = int(utc_offset)
            with open("timezone.json", mode="w") as f:
                json.dump(self.tz, f)
        elif ctx.author.id in self.tz:
            # return the timezone from the json file
            authortimezone = self.tz[ctx.author.id]
            if authortimezone < 0:
                await ctx.author.send(f"Your timezone: (UTC{authortimezone})")
            elif authortimezone >= 0:
                await ctx.author.send(f"Your timezone: (UTC+{authortimezone})")
        await ctx.message.delete()
コード例 #12
0
ファイル: core.py プロジェクト: kerrycobb/GPS-Utils
 def to_df(self):
     if not self.waypoints:
         self.get_waypoints()
     data = []
     tf = TimezoneFinder()
     for wp in self.waypoints:
         d = collections.OrderedDict()
         d["name"] = wp.name
         d["latitude"] = wp.latitude
         d["longitude"] = wp.longitude
         d["elev (m)"] = wp.elevation
         if wp.time:
             local_tz = tf.certain_timezone_at(lng=wp.longitude,
                                               lat=wp.latitude)
             local_dt = wp.time.replace(tzinfo=timezone.utc).astimezone(
                 tz=tz.gettz(local_tz))
             d["year (local)"] = local_dt.year
             d["month (local)"] = local_dt.month
             d["day (local)"] = local_dt.day
             d["time (local)"] = str(local_dt.time().strftime("%H:%M"))
             d["timezone (local)"] = local_tz
             d["year (UTC)"] = wp.time.year
             d["month (UTC)"] = wp.time.month
             d["day (UTC)"] = wp.time.day
             d["time (UTC)"] = str(wp.time.time().strftime("%H:%M"))
         else:
             d["year (local)"] = None
             d["month (local)"] = None
             d["day (local)"] = None
             d["time (local)"] = None
             d["timezone (local)"] = None
             d["year (UTC)"] = None
             d["month (UTC)"] = None
             d["day (UTC)"] = None
             d["time (UTC)"] = None
         data.append(d)
     df = pd.DataFrame(data)
     return df
コード例 #13
0
ファイル: time_test.py プロジェクト: leonov-anton/OZON
import requests
import json
import timezonefinder

# req = requests.get('http://api.geonames.org/timezoneJSON?lat=47.01&lng=10.2&username=demo')
# req = req.json()
# print(req)

from timezonefinder import TimezoneFinder

TimezoneFinder.using_numba()  # this is a static method returning True or False

tf = TimezoneFinder()
# tf = TimezoneFinder(in_memory=True) # to use the faster "in-memory" mode
# tf = TimezoneFinder(bin_file_location='path/to/files') # to use data files from another location

longitude, latitude = 13.358, 52.5061
print(tf.timezone_at(lng=55.028395, lat=61.646646))  # returns 'Europe/Berlin'
print(tf.certain_timezone_at(lng=longitude,
                             lat=latitude))  # returns 'Europe/Berlin'
コード例 #14
0
def getTimezone(latit, longit, date):

    # Esmalt leiame TimzoneFinderiga ajavööndi kujul näiteks "Europe/Tallinn"
    tzFinder = TimezoneFinder()
    tz_string = tzFinder.certain_timezone_at(lng=longit, lat=latit)
    timezone = pytz.timezone(tz_string)
    print(timezone, " timezone")

    # Kui ajavöönd on leitud siis leiame mis on selle konkreetse ajavööndi erinevus UTC ajast
    if (timezone is not None):
        currentDate = date
        date_time_str = currentDate + ' 12:00:00.000000'
        date_time_obj = datetime.datetime.strptime(date_time_str,
                                                   '%Y-%m-%d %H:%M:%S.%f')
        print(date_time_obj)
        utc_offset = timezone.utcoffset(date_time_obj)
        print(utc_offset)
    else:
        return "NODATA"

    print(str(utc_offset))

    # Järgmiste kui-laustega teeme kindaks ajavööndi, et see kümnendsüsteemis edastada.
    # Kui ajavöönd on negatiivne siis võtame ühtedelt kohtadelt soovitud info aga
    # kui positiivne siis peame soovitud info mujalt kätte saama.
    # Arvestame ka ajavööndeid, mis erinevad 15, 30 või 45 min võrra
    timezone = 0
    utcStr = str(utc_offset)
    first = utcStr[0]
    if (first == "-"):
        timezone = -1
        hour = utcStr[8:10]
        timezone = int(hour) - 24
        if (utcStr[11:13] != "00"):
            if (utcStr[11:13] == "15"):
                timezone -= 0.25
            if (utcStr[11:13] == "30"):
                timezone -= 0.5
            if (utcStr[11:13] == "45"):
                timezone -= 0.75
    else:
        if (utcStr[1:2] == ":"):
            hour = utcStr[0:1]
            timezone = hour
            print(utcStr[2:4])
            if (utcStr[2:4] != "00"):
                if (utcStr[2:4] == "15"):
                    timezone += 0.25
                if (utcStr[2:4] == "30"):
                    timezone += 0.5
                if (utcStr[2:4] == "45"):
                    timezone += 0.75
        else:
            hour = utcStr[0:2]
            timezone = hour
            print(utcStr[3:5])
            if (utcStr[3:5] != "00"):
                if (utcStr[3:5] == "15"):
                    timezone += 0.25
                if (utcStr[3:5] == "30"):
                    timezone += 0.5
                if (utcStr[3:5] == "45"):
                    timezone += 0.75

    # Tagastame ajavööndi täisarvuna
    return timezone
コード例 #15
0
ファイル: example.py プロジェクト: MrMinimal64/timezonefinder
from timezonefinder import TimezoneFinder

TimezoneFinder.using_numba()  # this is a static method returning True or False

tf = TimezoneFinder()
# or
tf = TimezoneFinder(in_memory=True)

longitude, latitude = 13.358, 52.5061
tf.timezone_at(lng=longitude, lat=latitude)  # returns 'Europe/Berlin'
tf.certain_timezone_at(lng=longitude, lat=latitude)  # returns 'Europe/Berlin'

longitude = 12.773955
latitude = 55.578595
tf.closest_timezone_at(lng=longitude, lat=latitude)  # returns 'Europe/Copenhagen'

longitude = 42.1052479
latitude = -16.622686
tf.closest_timezone_at(lng=longitude, lat=latitude, delta_degree=2, exact_computation=True, return_distances=True,
                       force_evaluation=True)

tf.get_geometry(tz_name='Africa/Addis_Ababa', coords_as_pairs=True)
tf.get_geometry(tz_id=400, use_id=True)


# To maximize the chances of getting a result in a Django view it might look like:

def find_timezone(request, lat, lng):
    lat = float(lat)
    lng = float(lng)
コード例 #16
0
    'пятниц': 4,
    'пятница': 4,
    'пятницу': 4,
    'суббот': 5,
    'суббота': 5,
    'субботу': 5,
    'воскресенье': 6
}
week_day_pattern = str(
    r'((\b(пн|вт|вторник|ср|чт|четверг|пт|сб|вс|воскресенье)\b)|(понедель|сред(у|a)|пятниц|суббот))'
)

tf = TimezoneFinder()
longitude = int(37)
latitude = int(55)
msc_tz = pytz.timezone(tf.certain_timezone_at(lng=longitude, lat=latitude))


def start(update, context):
    btn = [[KeyboardButton('help'), KeyboardButton('todo list')]]
    name = update.message.from_user['first_name']
    msg = f'Привет, {name}! Я бот который поможет не забыть о твоих планах. ⏰ \n\n' \
          'Напиши сообщение которое содержит время в формате ЧЧ:ММ чтобы добавить напоминание на сегодня.\n' \
          'Или укажи дату в формета ДД.ММ.ГГ. Или можно написать в сообщении "завтра" так же указав время или ' \
          'напиши в какой ближайший день недели. \n' \
          'Я пришлю тебе сообщение в указанное время.🔖\n' \
          'Написав todo list можно просматривать и управлять своими напоминаниями. 📝\n' \
          'Напиши help если захочешь прочитать это сообщение снова.\n\n' \
          'Если не хочется писать, можно нажать на кнопки ниже.'
    markup = ReplyKeyboardMarkup(btn,
                                 one_time_keyboard=False,
コード例 #17
0
Tr_K = Tr_K.where(Tr_K != -9999)
Tr_K = Tr_K * .1

aoi_met = daymetpy.daymet_timeseries(
    lon=center[0], lat=center[1], start_year=2002,
    end_year=2002)  # used to estimate mock params for aoi

import pvlib
import datetime
from timezonefinder import TimezoneFinder

time = pd.to_datetime(datetime.datetime(2002, 8, 3, 10, 4))
time = pd.DatetimeIndex([time])
tf = TimezoneFinder(in_memory=True)
timezone = tf.certain_timezone_at(lng=center[0], lat=center[1])
time = time.tz_localize(timezone)
solar_df = pvlib.solarposition.get_solarposition(
    time, center[1],
    center[0])  # can be made more accurate with temp and pressure from daymet

ltype = "Landsat5"

if ltype in ['Landsat4', 'Landsat5', 'Landsat7']:
    thermal_band = '6'
    # "wb" coefficients from Trezza et al. 2008
    band_sur_dict = {'1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '7': 6}

    wb_dict = {
        '1': 0.254,
        '2': 0.149,
コード例 #18
0
class GenerateTimezoneMask(BasePlugin):

    """
    A plugin to create masks for regions of a geographic grid that are on different
    timezones. The resulting masks can be used to isolate data for specific
    timezones from a grid of the same shape as the cube used in this plugin
    to generate the masks.
    """

    def __init__(self, include_dst=False, time=None, groupings=None):
        """
        Configure plugin options to generate the desired ancillary.

        Args:
            include_dst (Optional[bool]):
                If True, find and use the UTC offset to a grid point including
                the effect of daylight savings.
            time (Optional[str]):
                A datetime specified in the format YYYYMMDDTHHMMZ at which to
                calculate the mask (UTC). If daylight savings are not included
                this will have no impact on the resulting masks.
            groupings (Optional[Dict[int, List[int, int]]]):
                A dictionary specifying how timezones should be grouped if so
                desired. This dictionary takes the form::

                    {-9: [-12, -5], 0:[-4, 4], 9: [5, 12]}

                The numbers in the lists denote the inclusive limits of the
                groups. This is of use if data is not available at hourly
                intervals.
        """
        try:
            importlib.util.find_spec("timezonefinder")
        except ImportError as err:
            raise err
        else:
            from timezonefinder import TimezoneFinder

        self.tf = TimezoneFinder()
        self.time = time
        self.include_dst = include_dst
        self.groupings = groupings

    def _set_time(self, cube):
        """
        Set self.time to a datetime object specifying the date and time for
        which the masks should be created. self.time is set in UTC.

        Args:
            cube (iris.cube.Cube):
                The cube from which the validity time should be taken if one
                has not been explicitly provided by the user.
        """
        if self.time:
            self.time = datetime.strptime(self.time, "%Y%m%dT%H%MZ")
            self.time = pytz.utc.localize(self.time)
        else:
            try:
                self.time = cube.coord("time").cell(0).point
                self.time = pytz.utc.localize(self.time)
            except CoordinateNotFoundError:
                msg = (
                    "The input cube does not contain a 'time' coordinate. "
                    "As such a time must be provided by the user."
                )
                raise ValueError(msg)

    @staticmethod
    def _get_coordinate_pairs(cube):
        """
        Create an array containing all the pairs of coordinates that describe
        y-x points in the grid.

        Args:
            cube (iris.cube.Cube):
                The cube from which the y-x grid is being taken.
        Returns:
            numpy.array:
                A numpy array containing all the pairs of coordinates that describe
                the y-x points in the grid. This array is 2-dimensional, with
                shape (2,  (len(y-points) * len(x-points))).
        """
        if lat_lon_determine(cube) is not None:
            yy, xx = transform_grid_to_lat_lon(cube)
        else:
            latitudes = cube.coord("latitude").points
            longitudes = cube.coord("longitude").points.copy()

            # timezone finder works using -180 to 180 longitudes.
            if (longitudes > 180).any():
                longitudes[longitudes > 180] -= 180
                if ((longitudes > 180) | (longitudes < -180)).any():
                    msg = (
                        "TimezoneFinder requires longitudes between -180 "
                        "and 180 degrees. Longitude found outside that range."
                    )
                    raise ValueError(msg)
            yy, xx = np.meshgrid(latitudes, longitudes, indexing="ij")

        return np.stack([yy.flatten(), xx.flatten()], axis=1)

    def _calculate_tz_offsets(self, coordinate_pairs):
        """
        Loop over all the coordinates provided and for each calculate the
        offset from UTC in seconds.

        TimezoneFinder returns a string representation of the timezone for a
        point if it is defined, e.g. "America/Chicago", otherwise it returns
        None.

        For points without a national timezone (point_tz = None), usually over
        the sea, the nautical timezone offset is calculated which is based upon
        longitude. These are 15 degree wide bands of longitude, centred on the
        Greenwich meridian; note that the bands corresponding to UTC -/+ 12
        hours are only 7.5 degrees wide. Here longitudes are enforced between
        -180 and 180 degrees so the timezone offset can be calculated as:

            offset in hours   = np.around(longitude / 15)
            offset in seconds = 3600 * np.around(longitude / 15)

        Args:
            coordinate_pairs (numpy.array):
                A numpy array containing all the pairs of coordinates that describe
                the y-x points in the grid. This array is 2-dimensional, being
                2 by the product of the grid's y-x dimension lengths.
        Returns:
            numpy.array:
                A 1-dimensional array of grid offsets with a length equal
                to the product of the grid's y-x dimension lengths.
        """
        grid_offsets = []
        for latitude, longitude in coordinate_pairs:
            point_tz = self.tf.certain_timezone_at(lng=longitude, lat=latitude)

            if point_tz is None:
                grid_offsets.append(3600 * np.around(longitude / 15))
            else:
                grid_offsets.append(self._calculate_offset(point_tz))

        return np.array(grid_offsets, dtype=np.int32)

    def _calculate_offset(self, point_tz):
        """
        Calculates the offset in seconds from UTC for a given timezone, either
        with or without consideration of daylight savings.

        Args:
            point_tz (str):
                The string representation of the timezone for a point
                e.g. "America/Chicago",
        Returns:
            int:
                Timezone offset from UTC in seconds.
        """
        # The timezone for Ireland does not capture DST:
        # https://github.com/regebro/tzlocal/issues/80
        if point_tz == "Europe/Dublin":
            point_tz = "Europe/London"

        target = timezone(point_tz)
        local = self.time.astimezone(target)
        offset = local.utcoffset()

        if not self.include_dst:
            offset -= local.dst()

        return int(offset.total_seconds())

    def _create_template_cube(self, cube):
        """
        Create a template cube to store the timezone masks. This cube has only
        one scalar coordinate which is time, denoting when it is valid; this is
        only relevant if using daylight savings. The attribute
        includes_daylight_savings is set to indicate this.

        Args:
            cube (iris.cube.Cube):
                A cube with the desired grid from which coordinates are taken
                for inclusion in the template.
        Returns:
            iris.cube.Cube:
                A template cube in which each timezone mask can be stored.
        """
        time_point = np.array(self.time.timestamp(), dtype=np.int64)
        time_coord = iris.coords.DimCoord(
            time_point,
            "time",
            units=Unit("seconds since 1970-01-01 00:00:00", calendar="gregorian"),
        )

        for crd in cube.coords(dim_coords=False):
            cube.remove_coord(crd)
        cube.add_aux_coord(time_coord)

        attributes = generate_mandatory_attributes([cube])
        attributes["includes_daylight_savings"] = str(self.include_dst)

        return create_new_diagnostic_cube(
            "timezone_mask", 1, cube, attributes, dtype=np.int8
        )

    def _group_timezones(self, timezone_mask):
        """
        If the ancillary will be used with data that is not available at hourly
        intervals, the masks can be grouped to match the intervals of the data.
        For example, 3-hourly interval data might group UTC offsets:

            {12: [-12, -11], 9: [-10, -9, -8], 6: [-7, -6, -5], etc.}

        The dictionary specifying the groupings has a key, which provides the
        UTC offset to be used for the group. The list contains the UTC offsets
        that should be grouped together.

        The grouped UTC_offset cubes are collapsed together over the UTC_offset
        coordinate using iris.analysis.MIN. This means all the unmasked (0)
        points in each cube are preserved as the dimension is collapsed,
        enlarging the unmasked region to include all unmasked points from all
        the cubes.

        Args:
            timezone_mask (iris.cube.CubeList):
                A cube list containing a mask cube for each UTC offset that
                has been found necessary.
        Returns:
            iris.cube.CubeList:
                A cube list containing cubes created by blending together
                different UTC offset cubes to create larger masked regions.
        """
        grouped_timezone_masks = iris.cube.CubeList()
        for offset, group in self.groupings.items():

            # If offset key comes from a json file it will be a string
            offset = int(offset)

            constraint = iris.Constraint(
                UTC_offset=lambda cell: group[0] <= cell <= group[-1]
            )
            subset = timezone_mask.extract(constraint)
            if not subset:
                continue
            subset = subset.merge_cube()
            if subset.coord("UTC_offset").shape[0] > 1:
                subset = collapsed(subset, "UTC_offset", iris.analysis.MIN)
                subset.coord("UTC_offset").points = [offset]
            else:
                (point,) = subset.coord("UTC_offset").points
                subset.coord("UTC_offset").bounds = [point, point]
            grouped_timezone_masks.append(subset)
        return grouped_timezone_masks

    def process(self, cube):
        """
        Use the grid from the provided cube to create masks that correspond to
        all the timezones that exist within the cube. These masks are then
        returned in a single cube with a leading UTC_offset coordinate that
        differentiates between them.

        Args:
            cube (iris.cube.Cube):
                A cube with the desired grid. If no 'time' is specified in
                the plugin configuration the time on this cube will be used
                for determining the validity time of the calculated UTC offsets
                (this is only relevant if daylight savings times are being included).
        Returns:
            iris.cube.Cube:
                A timezone mask cube with a leading UTC_offset dimension. Each
                UTC_offset slice contains a field of ones (masked out) and zeros
                (masked in) that correspond to the grid points whose local times
                are at the relevant UTC_offset.
        """
        self._set_time(cube)
        coordinate_pairs = self._get_coordinate_pairs(cube)
        grid_offsets = self._calculate_tz_offsets(coordinate_pairs)

        # Model data is hourly, so we need offsets at hourly fidelity. This
        # rounds non-integer hour timezone offsets to the nearest hour.
        grid_offsets = np.around(grid_offsets / 3600).astype(np.int32)

        # Reshape the flattened array back into the original cube shape.
        grid_offsets = grid_offsets.reshape(cube.shape)

        template_cube = self._create_template_cube(cube)

        # Find the limits of UTC offset within the domain.
        min_offset = grid_offsets.min()
        max_offset = grid_offsets.max()

        # Create a cube containing the timezone UTC offset information.
        timezone_mask = iris.cube.CubeList()
        for offset in range(min_offset, max_offset + 1):
            zone = (grid_offsets != offset).astype(np.int8)
            coord = iris.coords.DimCoord(
                np.array([offset], dtype=np.int32),
                long_name="UTC_offset",
                units="hours",
            )
            tz_slice = template_cube.copy(data=zone)
            tz_slice.add_aux_coord(coord)
            timezone_mask.append(tz_slice)

        if self.groupings:
            timezone_mask = self._group_timezones(timezone_mask)

        timezone_mask = timezone_mask.merge_cube()
        timezone_mask.coord("UTC_offset").convert_units(TIME_COORDS["UTC_offset"].units)
        timezone_mask.coord("UTC_offset").points = timezone_mask.coord(
            "UTC_offset"
        ).points.astype(TIME_COORDS["UTC_offset"].dtype)
        timezone_mask.coord("UTC_offset").bounds = timezone_mask.coord(
            "UTC_offset"
        ).bounds.astype(TIME_COORDS["UTC_offset"].dtype)
        return timezone_mask
コード例 #19
0
ファイル: angleCalc.py プロジェクト: JA7ja/Suntrayce
gmaps = googlemaps.Client(key=os.environ['GEOCODE_KEY'])
tf = TimezoneFinder()

#variable initization
address = '144 East Ave., Ithaca, NY 148530'
print(address)

#Gets latitude and longitude from enteted address
geocode_result = gmaps.geocode(address)
latitude = geocode_result[0]['geometry']['location']['lat']
longitude = geocode_result[0]['geometry']['location']['lng']
print('Latitude: ' + str(latitude))
print('Longitude: ' + str(longitude))

#Gets timezone of location
timezone_str = tf.certain_timezone_at(lng=longitude, lat=latitude)
print(timezone_str)

#Conerts timezone to utc
timezone = pytz.timezone(timezone_str)
utc = datetime.utcnow()
timezone = utc + timezone.utcoffset(utc)
print(timezone)

#uses sunposition's sunpos function to get angles
Azimuth = sunpos(utc, latitude, longitude, 0)[0]
Zenith = sunpos(utc, latitude, longitude, 0)[1]
Elevation = 90 - Zenith

print("Sun Azimuth angle (east to west): " + str(Azimuth) +
      "\nSun Zenith angle: " + str(Zenith) +
コード例 #20
0
df_updated['lat'] = [None for i in range(0, len(df_updated))]
df_updated['lon'] = [None for i in range(0, len(df_updated))]
df_updated['elev_meters'] = [None for i in range(0, len(df_updated))]
df_updated['icao'] = [None for i in range(0, len(df_updated))]
df_updated['record_begin'] = [None for i in range(0, len(df_updated))]
df_updated['record_end'] = [None for i in range(0, len(df_updated))]

for i, row in df_updated.iterrows():
    old_row = df.loc[df['WBAN'] == row['wban'], :].values[0]
    beg = str(old_row[9])
    end = str(old_row[10])
    beg = beg[:4] + '-' + beg[4:6] + '-' + beg[-2:]
    end = end[:4] + '-' + end[4:6] + '-' + end[-2:]

    df_updated.loc[i, 'usaf'] = old_row[0]
    df_updated.loc[i, 'alternative_name'] = old_row[2]
    df_updated.loc[i, 'lat'] = old_row[6]
    df_updated.loc[i, 'lon'] = old_row[7]
    df_updated.loc[i, 'elev_meters'] = old_row[8]
    df_updated.loc[i, 'icao'] = old_row[5]
    df_updated.loc[i, 'record_begin'] = beg
    df_updated.loc[i, 'record_end'] = end
    tz_target = pytz.timezone(tf.certain_timezone_at(lng=old_row[7],
                                                     lat=old_row[6]))
    x = datetime(2000, 1, 1, 0, 0, 0)
    diff = pytz.utc.localize(x) - \
        tz_target.localize(x)
    df_updated.loc[i, 'utc_offset_min'] = int(diff.total_seconds() / 60)

df_updated.to_csv(out_file, index=False)
コード例 #21
0
            elif len(row) == 2:
                country, city = row
                lat, lng = None, None
            elif len(row) == 1:
                country = row[0]
                city = ''
                lat, lng = None, None

            if lat == '':
                if city == 'N/A' or city == None:
                    city = ''
                lat, lng = geocode_places[(country, city)]
            if lat != None:
                lat, lng = float(lat), float(lng)

            timezone = tf.certain_timezone_at(lat=lat,
                                              lng=lng)  # certain_timezone_at
            print(country, city, lat, lng, timezone, sep='\t')
        except Exception:
            pass
            # print(*row, sep="\t")

# with open('scihub_stats_2017_refined.tsv') as f:
#     reader = csv.reader(f, delimiter='\t')
#     reader.__next__() # drop header
#     for idx, row in enumerate(reader):
#         month, day, hour, minute, second, dayMinute, weekDay, yearDay, doi, IdByIp, IdByUser, country, city, lat, lng, latRound, lngRound = row
#         if len(lat) > 0:
#             pass
#             # lat, lng = float(lat), float(lng)
#             # timezone=tf.timezone_at(lat=lat, lng=lng) # certain_timezone_at
#         else: