Пример #1
0
    def post(self):
        '''Information from latitudes and longitudes '''

        location = request.get_json()
        location_str = f"{str(location['lat'])}, {str(location['lon'])}"
        geolocator = Nominatim(user_agent="location_dict", timeout=10)
        output = geolocator.reverse(location_str)

        tf = TimezoneFinder(in_memory=True)
        time_zone = tf.timezone_at(lng=location['lon'], lat=location['lat'])
        location_info = output.raw['address']
        location_info['time_zone'] = time_zone
        print(location_info)

        country_code = location_info["country_code"]

        location_info['continent'] = continent_mapping[country_code.upper()]

        return dict(location_info=location_info)
Пример #2
0
    def _get_timezone_from_builtins(self, locale):
        try:
            # This handles common city names, like "Dallas" or "Paris"
            # first get the lat / long.
            g = geocoder.osm(locale)

            # now look it up
            tf = TimezoneFinder()
            timezone = tf.timezone_at(lng=g.lng, lat=g.lat)
            return pytz.timezone(timezone)
        except Exception:
            pass

        try:
            # This handles codes like "America/Los_Angeles"
            return pytz.timezone(locale)
        except Exception:
            pass
        return None
Пример #3
0
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        city = tracker.get_slot("city")

        locator = Nominatim(user_agent="myGeocoder")
        location = locator.geocode(city)

        tf = TimezoneFinder()
        latitude, longitude = location.latitude, location.longitude
        time_zone_find = tf.timezone_at(
            lng=longitude, lat=latitude)  # returns 'Europe/Berlin'
        show_time = timezone(time_zone_find)
        sa_time = datetime.now(show_time)
        output = sa_time.strftime('%Y-%m-%d_%H-%M-%S')

        dispatcher.utter_message(text=output)

        return []
Пример #4
0
def adjust_timezones(df, time_col, latitude_col, longitude_col, inplace=False):
    """
    Calculates timezone offset and adjusts date columns accordingly. This is done because GLOBE data uses UTC timezones and it can be useful to have the time adjusted to the local observation time.

    Parameters
    ----------
    df : pd.DataFrame
        The DataFrame to adjust time zones for
    time_col : str
        The column that contains the time zone data
    latitude_col : str
        The column that contains latitude data
    longitude_col : str
        The column that contains longitude data
    inplace : bool, default=False
        Whether to return a new DataFrame. If True then no DataFrame copy is not returned and the operation is performed in place.

    Returns
    -------
    pd.DataFrame or None
        A DataFrame with its time entry adjusted to its local timezone. If `inplace=True` it returns None.
    """
    tf = TimezoneFinder()

    def convert_timezone(time, latitude, longitude):
        utc_tz = pd.to_datetime(time, utc=True)
        local_time_zone = timezone(tf.timezone_at(lng=longitude, lat=latitude))
        return utc_tz.astimezone(local_time_zone)

    time_zone_converter = np.vectorize(convert_timezone)

    if not inplace:
        df = df.copy()

    df[time_col] = time_zone_converter(
        df[time_col].to_numpy(),
        df[latitude_col].to_numpy(),
        df[longitude_col].to_numpy(),
    )

    if not inplace:
        return df
    def update_local_timezone(self):

        #############################################################################################################
        #
        # set_city_tz_date_time() uses package TimezoneFinder
        # https://github.com/MrMinimal64/timezonefinder
        #
        # timezone_at()
        #   This is the default function to check which timezone a point lies within
        #      - (similar to tzwheres tzNameAt()).
        #      - If no timezone has been found, None is being returned.
        #   PLEASE NOTE: This approach is optimized for speed and the common case to only query
        #   points within a timezone. The last possible timezone in proximity is always returned
        #   (without checking if the point is really included).
        #
        #   So results might be misleading for points outside of any timezone.
        #
        #   Example:
        #   longitude = 13.358
        #   latitude = 52.5061
        #   tf.timezone_at(lng=longitude, lat=latitude) # returns 'Europe/Berlin'
        #
        # certain_timezone_at()
        #   NOTE: The timezone polygons do NOT follow the shorelines any more! This causes the
        #   computed distance from a timezone polygon to be not really meaningful/accurate.
        #
        #   Only use this when the point is not inside a polygon (simply computes and compares the
        #   distances to the polygon boundaries!). This returns the closest timezone of all polygons
        #   within +-1 degree lng and +-1 degree lat (or None).
        #
        #   Example:
        #   longitude = 12.773955
        #   latitude = 55.578595
        #   tf.closest_timezone_at(lng=longitude, lat=latitude) # returns 'Europe/Copenhagen'
        #
        #############################################################################################################

        tf = TimezoneFinder()

        # self.local_timezone will be of string format 'Europe/London'
        self.local_timezone = tf.closest_timezone_at(lng=self.geocode_lng,
                                                     lat=self.geocode_lat)
Пример #6
0
def setTimezone(update, context):
    message = ""
    if calledTimezone.get(update.message.chat.id, False):
        try:
            tf = TimezoneFinder()
            timezone = tf.timezone_at(lng = update.message.location.longitude, lat = update.message.location.latitude)
            document = mongo.db.itemsList.find({"_id": update.message.chat.id})
            if len(list(document)) == 1:
                document.rewind()
                mongo.db.itemsList.update_one({"_id": update.message.chat.id}, {"$set": {"timezone": timezone}})
                message = f"Timezone updated to {timezone}!"
            else:
                mongo.db.itemsList.insert_one({"_id": update.message.chat.id, "lists": [], "timezone": timezone})
                message = f"Timezone setted!"
            update.message.reply_text(message)
            calledTimezone[update.message.chat.id] = False
        except StopIteration:
            calledTimezone[update.message.chat.id] = False
            print("StopIteration error: Rewinding Cursor object.")
            update.message.reply_text("Internal server error, sorry for the incoveniences")
Пример #7
0
 def get_LMST(self, latitud, longitud):  #HORA SIDERAL LOCAL
     #ut1= datetime(self.fecha_año,self.fecha_mes,self.fecha_dia,self.fecha_hora,self.fecha_min,self.fecha_seg)
     ut1 = Time(self.fecha_hora,
                scale='utc',
                location=(self.LONG_grados, self.LAT_grados))
     tf = TimezoneFinder()
     tz = tf.timezone_at(lng=longitud, lat=latitud)
     data = np.genfromtxt('timeZones.txt',
                          delimiter='\t',
                          names=True,
                          dtype=None,
                          encoding='utf-8')
     indice = np.where(data['TimeZoneId'] == tz)
     if (tz == None):
         print("NO EXISTE ZONA HORARIA")
         y = 0
     else:
         y = data[indice][0][3] * 15
     self.LMST_grados = Angle(ut1.sidereal_time('mean'),
                              unit=u.deg).rad - y * math.pi / 180
Пример #8
0
    def __init__(self, device=DEFAULT_GPS_DEVICE):
        self.serialcom = serial.Serial(device,
                                       baudrate=9600,
                                       bytesize=8,
                                       parity='N',
                                       stopbits=1,
                                       timeout=0.5,
                                       rtscts=0)
        self.status = 0
		self.gprmc_status = 0
		self.gpgga_status = 0
		self.lat = 0
		self.lon = 0
		self.dataline = ''
		self.tf = TimezoneFinder()
		self.tzinfo = utc
		
		duration = 60/2 #minutes
		rate_gps = 10
		self.array_dataline=[''] * duration * rate_gps
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
Пример #10
0
    def sunset_sunrise(self, long, lat, day, month, year):
        # from Sun import Sun
        coords = {'longitude': long, 'latitude': lat}
        date = {'day': day, 'month': month, 'year': year}
        sun = Sun()

        tf = TimezoneFinder()
        timezone = tf.timezone_at(lng=long, lat=lat)

        # Sunrise time UTC (decimal, 24 hour format)
        sunrise = self.convert_time(
            timezone,
            sun.getSunriseTime(coords, date)['decimal'], date)

        # Sunset time UTC (decimal, 24 hour format)
        sunset = self.convert_time(timezone,
                                   sun.getSunsetTime(coords, date)['decimal'],
                                   date)

        return sunrise, sunset
Пример #11
0
def timezones():

    if request.method == 'GET':
        return render_template('timezones.html')

    else:
        df = pd.read_csv(request.files.get("timezone_file"))
        df.index = df.timestamp
        df.index = pd.to_datetime(df.index)
        df.index = df.index.tz_localize('UTC')
        tf = TimezoneFinder(in_memory=True)
        timezones = []
        for index, row in df.iterrows():
            latitude = (row['latitude'])
            longitude = (row['longitude'])
            print(latitude, longitude)
            try:
                timezones.append(tf.timezone_at(lng=longitude, lat=latitude))
            except:
                timezones.append('N/A')

        df['timezone'] = timezones

        converted = []
        for index, row in df.iterrows():
            timezone = row['timezone']
            try:
                convert = index.tz_convert(timezone)
                converted.append(convert)
            except:
                converted.append('N/A')

        df['local_timestamp'] = converted
        df['local_time'] = df['local_timestamp'].astype(str).str[:19]
        #df = df.reset_index()
        print(df.columns)
        resp = make_response(df.to_csv())
        resp.headers[
            "Content-Disposition"] = "attachment; filename=timezone_export.csv"
        resp.headers["Content-Type"] = "text/csv"
        return resp
Пример #12
0
    def __init__(self, bootstrap, debug_enabled):
        """
        Constructor

        Args:
            bootstrap (dict): bootstrap objects
            debug_enabled (bool): flag to set debug level to logger
        """
        # init
        CleepModule.__init__(self, bootstrap, debug_enabled)

        # members
        self.hostname = Hostname(self.cleep_filesystem)
        self.sun = Sun()
        self.sunset = None
        self.sunrise = None
        self.suns = {
            "sunset": 0,
            "sunset_iso": "",
            "sunrise": 0,
            "sunrise_iso": ""
        }
        self.timezonefinder = TimezoneFinder()
        self.timezone_name = None
        self.timezone = None
        self.time_task = None
        self.sync_time_task = None
        self.__clock_uuid = None
        # code from https://stackoverflow.com/a/106223
        self.__hostname_pattern = (
            r"^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*"
            r"([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$")

        # events
        self.time_now_event = self._get_event("parameters.time.now")
        self.time_sunrise_event = self._get_event("parameters.time.sunrise")
        self.time_sunset_event = self._get_event("parameters.time.sunset")
        self.hostname_update_event = self._get_event(
            "parameters.hostname.update")
        self.country_update_event = self._get_event(
            "parameters.country.update")
Пример #13
0
def get_timestamp(image_path=None,
                  exif_data=None,
                  format_string="%Y:%m:%d %H:%M:%S"):
    """
    Get the time stamp of an image and parse it into a `datetime` object with the given format string.

    If originating from a Sentera or DJI sensor, the format of the tag will likely be that of the default input.
    However, other sensors may store timestamps in other formats.

    :param image_path: the full path to the image (optional if `exif_data` provided)
    :param exif_data: the exif dictionary for the image (optional to speed up processing)
    :param format_string: Format code, as a string, to be used to parse the image timestamp.
    :return: **datetime_obj**: Parsed timestamp, in the format specified by the input format string.
    :raises: ParsingError
    """
    try:
        datetime_obj = datetime.strptime(
            exif_data["EXIF DateTimeOriginal"].values, format_string)
    except KeyError:
        logger.error("Couldn't determine image timestamp.")
        raise ParsingError("Couldn't determine image timestamp.")
    except ValueError:
        logger.error(
            "Couldn't parse found timestamp with given format string.")
        raise ValueError(
            "Couldn't parse found timestamp with given format string.")

    make, model = get_make_and_model(image_path=image_path,
                                     exif_data=exif_data)
    if make == "Sentera":
        datetime_obj = pytz.utc.localize(datetime_obj)
    elif make == "DJI":
        lat, lon = get_lat_lon(image_path=image_path, exif_data=exif_data)
        timezone = pytz.timezone(TimezoneFinder().timezone_at(lng=lon,
                                                              lat=lat))
        datetime_obj = timezone.localize(datetime_obj)
    else:
        logger.warning(
            "Sensor make isn't supported for timezone aware datetimes.")

    return datetime_obj
Пример #14
0
def subscriptionForecast(userId):
    city = getSubscription(userId)
    if getLanguage(userId) == 'ukr':
        f = f'Агов, ось твій прогноз на день в м. {city}😄\n'
    elif getLanguage(userId) == 'rus':
        f = f'Эй, лови свой прогноз на день в г. {city}😄\n'
    else:
        f = f'Hey, get your daily forecast in {city}😄\n'
    sticker = ''
    forecaster = owm.three_hours_forecast(getSubscription(userId))
    forecast = forecaster.get_forecast()
    weather_list = forecast.get_weathers()
    observation = owm.weather_at_place(getSubscription(userId))
    l = observation.get_location()
    tz = TimezoneFinder().timezone_at(lng=l.get_lon(), lat=l.get_lat())
    local = pytz.utc.localize(datetime.utcnow()).astimezone(pytz.timezone(tz))
    loc = local.isoformat()
    diff = int(loc[26] + loc[27] + loc[28]) - 2
    for weather in weather_list:
        temp = round(weather.get_temperature('celsius')['temp'], 1)
        status = translateStatus(weather.get_status(), userId)[0]
        hours = (weather.get_reference_time('date') +
                 timedelta(hours=diff)).hour
        if hours < 3 or 12 <= hours < 15:
            sticker = '🕛'
        elif 3 <= hours < 6 or 15 <= hours < 18:
            sticker = '🕒'
        elif 6 <= hours < 9 or 18 <= hours < 21:
            sticker = '🕕'
        elif 9 <= hours < 12 or hours >= 21:
            sticker = '🕘'
        if hours < 10:
            hours = '0' + str(hours)
        if (weather.get_reference_time('date') + timedelta(hours=diff)).day is (
                datetime.now() + timedelta(days=0, hours=diff)).day or \
                (weather.get_reference_time('date') + timedelta(hours=diff)).day is (
                datetime.now() + timedelta(days=1, hours=diff)).day and \
                (weather.get_reference_time('date') + timedelta(hours=diff)).hour is 0:
            f += sticker + " " + str(hours) + ":00 - " + str(
                temp) + "°C, " + status + "\n"
    return f
Пример #15
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)
Пример #16
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()
Пример #17
0
class Location(object):

    _locator = CachedGeoLocator().load()
    _tf = TimezoneFinder()

    @classmethod
    def save_cache(cls):
        if cls._locator is not None:
            cls._locator.save()

    def __init__(self, identifier, name, coords):
        self.identifier = identifier
        self.name = name
        if coords is None:
            loc = self._locator.get_location(name)
            self.coords = (loc['lng'], loc['lat'])
        else:
            self.coords = coords
        self.timezone = None

    def lat(self):
        return self.coords[1]

    def lng(self):
        return self.coords[0]

    def asLatLongTuple(self):
        return (self.lat(), self.lng())

    def timezone_name(self):
        return self._tf.timezone_at(lng=self.lng(), lat=self.lat())

    def get_timezone(self):
        if self.timezone is None:
            self.timezone = pytz.timezone(self.timezone_name())
        return self.timezone

    def __str__(self):
        return "%s: identifier=%s, name=%s" % (type(self).__name__,
                                               self.identifier, self.name)
Пример #18
0
def extract_time(t, lon, lat):
    from_zone = tz.tzutc()
    tf = TimezoneFinder()
    ts = [
        time.strftime('%Y-%m-%d %H:%M:%S',
                      time.strptime(date_string, '%a %b %d %H:%M:%S +0000 %Y'))
        for date_string in t
    ]
    utc = [datetime.strptime(x, '%Y-%m-%d %H:%M:%S') for x in ts]
    timezone_str = [
        tf.timezone_at(lng=lon[i], lat=lat[i]) for i in range(len(lon))
    ]

    to_zone = [
        pytz.timezone(x) if x is not None else pytz.timezone('UTC')
        for x in timezone_str
    ]
    local_time = [
        utc[i].replace(tzinfo=from_zone).astimezone(to_zone[i])
        for i in range(len(to_zone))
    ]
    return [[x.year, x.month, x.day, x.hour, x.minute] for x in local_time]
Пример #19
0
def restart_jobs(dp):
    for chat_id in dp.chat_data:
        if 'job' in dp.chat_data[chat_id]:
            tf = TimezoneFinder()
            tz_at_home = tf.timezone_at(lng=dp.chat_data[chat_id]['lon'],
                                        lat=dp.chat_data[chat_id]['lat'])
            hometz = pytz.timezone(tz_at_home)

            reminder_time = datetime.utcnow()
            input_time = datetime.strptime(dp.chat_data[chat_id]['time'],
                                           "%H:%M")
            reminder_time = reminder_time.replace(hour=input_time.hour,
                                                  minute=input_time.minute,
                                                  second=input_time.minute)
            reminder_time = (reminder_time -
                             hometz.utcoffset(reminder_time)).time()

            job_context = ChatContext(chat_id, dp.chat_data[chat_id])
            new_job = dp.job_queue.run_daily(send_home_monitor,
                                             reminder_time,
                                             context=job_context)
            dp.bot_data[chat_id] = new_job
Пример #20
0
    def is_future_sample_date(self, date_str, time_str, site_id):
        site = Site.objects.get_or_none(id=site_id)

        if site is None or site.location is None:
            return False

        x = site.location.x
        y = site.location.y

        tf = TimezoneFinder()
        tz_str = tf.timezone_at(lng=x, lat=y) or "UTC"
        tzinfo = tz.gettz(tz_str)
        sample_date = parse_datetime("{} {}".format(date_str, time_str))

        if sample_date is None:
            return False

        sample_date = sample_date.replace(tzinfo=tzinfo)
        todays_date = timezone.now().astimezone(tzinfo)
        delta = todays_date - sample_date

        return delta.days < 0
Пример #21
0
 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
Пример #22
0
    def __init__(
        self,
        include_dst: bool = False,
        time: Optional[str] = None,
        groupings: Optional[Dict[int, List[int]]] = None,
    ) -> None:
        """
        Configure plugin options to generate the desired ancillary.

        Args:
            include_dst:
                If True, find and use the UTC offset to a grid point including
                the effect of daylight savings.
            time:
                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:
                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
Пример #23
0
 def __init__(self):
     self.timezone_finder = TimezoneFinder()
     self.sensor_array = Sensors(mock=True)
     try:
         self.vessel = Vessel.objects.latest(field_name="created_at")
     except Vessel.DoesNotExist as error:
         logger.debug("LoggerJob __init__ - {0}".format(error))
     try:
         most_recent_day = Day.objects.filter(
             vessel=self.vessel).latest("created_at")
     except (AttributeError, Day.DoesNotExist) as error:
         logger.warning(
             "Previous Day not found. One will be created "
             "at the beginning of the next hour if a vessel is defined "
             "at POST /vessel/")
     try:
         previous_entry = Hour.objects.filter(day=most_recent_day).latest()
         self.update_sensor_array_by_previous_entry(previous_entry)
     except (UnboundLocalError, Hour.DoesNotExist) as error:
         logger.info(
             "Previous Hour entry not found. One will be created "
             "at the beginning of the next hour if a vessel is defined "
             "at POST /vessel/")
Пример #24
0
def determine_timezone(latitude: float, longitude: float):
    """
    Determine the timezone for a given set of coordinates

    Parameters
    ==========
    latitude : 'float'
        Latitude value
    longitude : 'float'
        Longitude value

    Returns
    =======
    timezone: 'str'
        Timezone string for given coordinates or 'None' in case of an error
    """

    assert type(latitude) in [float, int]
    assert type(longitude) in [float, int]

    tf = TimezoneFinder()
    timezone = tf.timezone_at(lng=longitude, lat=latitude)
    return timezone
Пример #25
0
def check_time():
    logger.info(f'Checking time...')
    client = MongoClient(MONGO_URL)
    collection = client[DB_NAME][COLLECTION_NAME]
    user_data = get_user_data(collection)

    for user in user_data:
        tz_name = TimezoneFinder().timezone_at(lat=user.latitude,
                                               lng=user.longitude)
        tz = timezone(tz_name)
        now = dt.now(tz)

        if dt.fromisoformat(user.dt) < now:
            try:
                notificate_user(user)
            except Exception as e:
                logger.exception(e)
            finally:
                set_user_sent_status(collection, user.user_id)

        time.sleep(.05)

    client.close()
def generate(start_date, end_date, data_file):
    """
    Generates the weather data and outputs to stdout.

    :param data_file: Absolute path to the source data file.
    :param start_date: The starting date to begin generating weather data for.
    :param end_date: The end date to stop generating weather date for.
    """
    location_records = []

    with open(data_file) as location_file:
        location_records = json.load(location_file)

    current_date = start_date

    while current_date <= end_date:
        current_month = current_date.datetime.month - 1

        for location in location_records:
            tf = TimezoneFinder()
            timezone_str = tf.timezone_at(lng=location['longitude'],
                                          lat=location['latitude'])
            tz = pytz.timezone(timezone_str)

            weather_condition = WeatherCondition(
                name=location['name'],
                latitude=location['latitude'],
                longitude=location['longitude'],
                elevation=location['elevation'],
                temperature=uniform(location['temps']['min'][current_month],
                                    location['temps']['max'][current_month]),
                datetime=current_date.astimezone(tz))

            weather_condition.calculate()
            print(weather_condition)

        current_date = current_date.replace(days=1)
Пример #27
0
def current_time(converted: str = None) -> None:
    """Says current time at the requested location if any, else with respect to the current timezone.

    Args:
        converted: Takes the phrase as an argument.
    """
    place = support.get_capitalized(phrase=converted) if converted else None
    if place and len(place) > 3:
        tf = TimezoneFinder()
        place_tz = geo_locator.geocode(place)
        coordinates = place_tz.latitude, place_tz.longitude
        located = geo_locator.reverse(coordinates, language='en')
        address = located.raw.get('address', {})
        city, state = address.get('city'), address.get('state')
        time_location = f'{city} {state}'.replace(
            'None', '') if city or state else place
        zone = tf.timezone_at(lat=place_tz.latitude, lng=place_tz.longitude)
        datetime_zone = datetime.now(pytz.timezone(zone))
        date_tz = datetime_zone.strftime("%A, %B %d, %Y")
        time_tz = datetime_zone.strftime("%I:%M %p")
        dt_string = datetime.now().strftime("%A, %B %d, %Y")
        if date_tz != dt_string:
            date_tz = datetime_zone.strftime("%A, %B %d")
            speaker.speak(
                text=
                f'The current time in {time_location} is {time_tz}, on {date_tz}.'
            )
        else:
            speaker.speak(
                text=f'The current time in {time_location} is {time_tz}.')
    else:
        if shared.called['report'] or shared.called['time_travel']:
            speaker.speak(
                text=
                f"The current time is, {datetime.now().strftime('%I:%M %p')}.")
            return
        speaker.speak(text=f"{datetime.now().strftime('%I:%M %p')}.")
Пример #28
0
def get_local_etc_timezone(latitude, longitude):
    '''
    This function gets the time zone at a given latitude and longitude in 'Etc/GMT' format.
    This time zone format is used in order to avoid issues caused by Daylight Saving Time (DST) (i.e., redundant or
    missing times in regions that use DST).
    However, note that 'Etc/GMT' uses a counter intuitive sign convention, where West of GMT is POSITIVE, not negative.
    So, for example, the time zone for Zurich will be returned as 'Etc/GMT-1'.

    :param latitude: Latitude at the project location
    :param longitude: Longitude at the project location
    '''

    # get the time zone at the given coordinates
    tf = TimezoneFinder()
    time = pytz.timezone(tf.timezone_at(lng=longitude, lat=latitude)).localize(
        datetime.datetime(2011, 1, 1)).strftime('%z')

    # invert sign and return in 'Etc/GMT' format
    if time[0] == '-':
        time_zone = 'Etc/GMT+' + time[2]
    else:
        time_zone = 'Etc/GMT-' + time[2]

    return time_zone
Пример #29
0
    def handleTime(self, intent, mic):
        print("handleTime")
        print(intent)
        if 'LocationKeyword' in intent['matches']:
            for location in intent['matches']['LocationKeyword']:
                geo = geocoder.osm(location)
                tzf = TimezoneFinder()
                tz = tzf.timezone_at(lng=geo.lng, lat=geo.lat)
                now = datetime.datetime.now(tz=timezone(tz))
                if now.minute == 0:
                    fmt = self.gettext("IT IS {t:%l} {t:%p} IN {l} RIGHT NOW.")
                else:
                    fmt = self.gettext(
                        "IT IS {t:%l}:{t:%M} {t:%p} IN {l} RIGHT NOW.")
                mic.say(fmt.format(l=location, t=now))
        else:
            now = datetime.datetime.now(tz=app_utils.get_timezone())
            if now.minute == 0:
                fmt = self.gettext("IT IS {t:%l} {t:%p}.")
            else:
                fmt = self.gettext("IT IS {t:%l}:{t:%M} {t:%p}.")
            mic.say(fmt.format(t=now))

        return True
Пример #30
0
def get_omer_time(user_data: UserData) -> Optional[str]:
    tz_name = TimezoneFinder().timezone_at(lat=user_data.latitude,
                                           lng=user_data.longitude)
    location = GeoLocation('',
                           user_data.latitude,
                           user_data.longitude,
                           time_zone=tz_name)
    calendar = ZmanimCalendar(60, geo_location=location, date=date.today())
    jcalendar = JewishCalendar.from_date(date.today())

    omer_day = jcalendar.day_of_omer()
    if not omer_day:
        return

    if jcalendar.is_assur_bemelacha(
    ) and jcalendar.is_tomorrow_assur_bemelacha():
        return
    elif jcalendar.is_tomorrow_assur_bemelacha():
        omer_time = calendar.candle_lighting()
    else:
        omer_time = calendar.tzais()

    if isinstance(omer_time, dt):
        return omer_time.isoformat()