def get_timezone_offset(self) -> Optional[str]: zipcode = self.get_rich_zipcode() if zipcode is None: return None tf = TimezoneFinder() longitude = zipcode['Longitude'] latitude = zipcode['Latitude'] timezone_name = tf.timezone_at(lng=longitude, lat=latitude) if timezone_name is None: return None return datetime.datetime.now(pytz.timezone(timezone_name)).strftime('%z')
def getTimeZone( location ): from timezonefinder import TimezoneFinder tf = TimezoneFinder( ) if isinstance( location, str ): location = getLocation( location ) elif not isinstance( location, RPNLocation ): raise ValueError( 'location name or location object expected' ) timezone_name = tf.timezone_at( lat = location.getLat( ), lng = location.getLong( ) ) if timezone_name is None: timezone_name = tf.closest_timezone_at( lat = location.getLat( ), lng = location.getLong( ) ) return timezone_name
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
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")
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
def get_time(self): """ Using TimezoneFinder().timezone_at() to cast given latitude and longitude into a string representation ex: "Asia/Tokyo" Details: print(timezone_string) # this print Etx/GMT-9 for lat=5.7 and 139.7 print(datetime.now(timezone("Asia/Tokyo"))) """ timezone_string = TimezoneFinder().timezone_at(lat=self.latitude, lng=self.longitude) time_now = datetime.now(timezone(timezone_string)) return time_now
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)
def getTime(tweet, latit, longit): #get timezone zone = TimezoneFinder().timezone_at(lng=longit, lat=latit) timezone = pytz.timezone(zone) #convert zone string to pytz format #convert to local time utc_time = dt.datetime.strptime( tweet["created_at"], '%a %b %d %H:%M:%S +0000 %Y').replace(tzinfo=pytz.UTC) local_time = utc_time.replace(tzinfo=pytz.utc).astimezone(timezone) # finaltime = local_time.strftime(format='%Y-%m-%d %H:%M:%S') return local_time
def main(): """Find the time of a given location. :return: A namedtuple, TimeZoneResult with location and time. """ location = str(input('Location : ')) geocode_result = Geocoder(API_KEY).geocode(location) coordinates = geocode_result.data[0]['geometry']['location'] location = geocode_result.data[0]['formatted_address'] timezone = TimezoneFinder().timezone_at(**coordinates) time = datetime.now(pytz.timezone(timezone)) return TimeZoneResult(location=location, time=time)
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()
def get_gps_data(): if config['sensors']['gps_enable']: try: # Reinitialise gpsd connection if it's broken for some reason if not gps_data['mode']: gpsd.connect() # Read some data packet = gpsd.get_current() # Deposit it into the global dict gps_data['mode'] = packet.mode gps_data['mode_text'] = gps_mode_text[gps_data['mode']] gps_data['sats'] = packet.sats gps_data['sats_valid'] = packet.sats_valid # Present some information if we have a fix if (gps_data['mode'] >= 2): gps_data['time'] = packet.get_time().replace( tzinfo=None, microsecond=0).isoformat() gps_data['time_local'] = packet.get_time( local_time=True).replace(tzinfo=None, microsecond=0).isoformat() gps_data['timezone'] = TimezoneFinder().timezone_at( lng=packet.lon, lat=packet.lat) gps_data['latitude'] = round(packet.lat, 4) gps_data['longitude'] = round(packet.lon, 4) gps_data['speed'] = int(packet.speed()) else: gps_data['time'] = None gps_data['time_local'] = None gps_data['timezone'] = None gps_data['latitude'] = None gps_data['longitude'] = None gps_data['speed'] = None # Information below is only obtainable from a 3D fix if (gps_data['mode'] >= 3): gps_data['altitude'] = int(packet.alt) else: gps_data['altitude'] = None except Exception as e: # Error has occurred, log it logger.error("Failed to get GPS data: " + str(e)) gps_data.clear() gps_data['enabled'] = True gps_data['mode'] = 0 gps_data['mode_text'] = gps_mode_text[gps_data['mode']] else: logger.warn('Request to read GPS data, but not enabled in config')
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
def process_request(self, request): user_time_zone = request.session.get('user_time_zone', None) user_time_zone = None try: if user_time_zone is None: ip = get_real_ip(request) if ip is None: tf = TimezoneFinder() print point = (request.user.userdata.address.longditude,request.user.userdata.address.latitude) user_time_zone = tf.timezone_at(*point) request.session['user_time_zone'] = user_time_zone else : freegeoip_response = requests.get('http://freegeoip.net/json/{0}'.format()) freegeoip_response_json = freegeoip_response.json() user_time_zone = freegeoip_response_json['time_zone'] if user_time_zone: request.session['user_time_zone'] = user_time_zone timezone.activate(pytz.timezone(user_time_zone)) except: pass return None
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
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]
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, account_id, region_id, identifier, name, coords=None, timezone_name=None, created_at=None): self.account_id = account_id self.region_id = region_id self.identifier = identifier self.name = name self.coords = coords self.timezone_name = timezone_name if created_at is None: self.created_at = dt.datetime.now() else: self.created_at = created_at if self.coords is None: # Use geolocation service to determine coords based on name of location loc = self._locator.get_location(name) self.coords = Coords(loc['lng'], loc['lat']) self.timezone_name = None if self.timezone_name is None: self.timezone_name = self._tf.timezone_at(lng=self.lng(), lat=self.lat()) def lat(self): return self.coords.latitude def lng(self): return self.coords.longitude def alt(self): return self.coords.altitude def asLatLongTuple(self): return (coords.latitude, coords.longitude) def get_timezone(self): return pytz.timezone(self.timezone_name) def distance_NM(self, to_location): return great_circle(self.asLatLongTuple(), self.to_location.asLatLongTuple()).miles def __repr__(self): return '<Location(region={self.region_id}, id={self.identifier}, name={self.name!r}, coords={self.coords}, tz={self.timezone_name})>'.format(self=self)
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
def filterhits(camera, data): # timezones tf = TimezoneFinder() zone = tf.timezone_at(lng=camera.lon, lat=camera.lat) timestamps = [] for record in data: timestamps.append(record['submission']['image']['timestamp']) instance = {} for timestamp in set(timestamps): instance[timestamp] = {'vehicles': set(), 'bikes': set(), 'people': set()} for record in data: if record['submission']['image']['timestamp'] == timestamp: worker = record['submission']['workerId'] bbox = Bbox(record['x1'], record['y1'], record['x2'], record['y2'], worker) # some have w = 0 or h = 0 if bbox.w * bbox.h > 0: instance[timestamp][record['type']].add(bbox) with open('camera_{}_points.csv'.format(camera.id), 'w') as f: f.write('year,month,day,hour,minute,type,count,x,y,url,url2,y,m,d,h,mi,camw,camh\n') for timestamp in sorted(instance.keys()): date, time = timestamp.split('T') y, m, d = date.split('-') h, mi, s = time.split(':') ts = timestamp.replace(':', '').replace('T', '_').replace('-', '') dt = datetime.datetime(year=int(y), month=int(m), day=int(d), hour=int(h), minute=int(mi), second=int(s), tzinfo=utc) lt = local_time(dt, zone) url = 'http://amos.cse.wustl.edu/mturk/reviewOutlines/{}/{}'.format(camera.id, ts) url2 = 'http://amos.cse.wustl.edu/image/{}/{}.jpg'.format(camera.id, ts) for htype in instance[timestamp].keys(): records = resolve_duplicates(list(instance[timestamp][htype])) for xx, yy in records: f.write('{yl},{ml},{dl},{hl},{mil},{tp},{cnt},{xx},{yy},{url},{url2},{y},{m},{d},{h},{mi},{camw},{camh}\n' .format(yl=lt.year, ml=lt.month, dl=lt.day, hl=lt.hour, mil=lt.minute, y=y, m=m, d=d, h=h, mi=mi, tp=htype, cnt=len(records), xx=xx, yy=yy, url=url, url2=url2, camw=camera.w, camh=camera.h))
def prepareResponse(self, res, data): if res != {}: tf = TimezoneFinder() if res.get("coord") and res["coord"] != None: data.update({ "latitude": res["coord"]["lat"], "longitude": res["coord"]["lon"], "local_timezone": timezone( tf.timezone_at(lng=res["coord"]["lon"], lat=res["coord"]["lat"])) }) if res.get("main") and res["main"] != None: data.update({ "temp": res["main"]["temp"], "feel": res["main"]["feels_like"], "min_temp": res["main"]["temp_min"], "max_temp": res["main"]["temp_max"], "pressure": res["main"]["pressure"], "humidity": res["main"]["humidity"] }) if res.get("weather") and res["weather"][0] != None: data.update({ "main": res["weather"][0]["main"], "desc": res["weather"][0]["description"], "icon": res["weather"][0]["icon"], }) if res.get("sys") and res["sys"] != None: data.update({ "country": res["sys"]["country"], "sunrise": datetime.datetime.fromtimestamp( res["sys"]["sunrise"], tz=timezone( tf.timezone_at(lng=res["coord"]["lon"], lat=res["coord"]["lat"]))), "sunset": datetime.datetime.fromtimestamp( res["sys"]["sunset"], tz=timezone( tf.timezone_at(lng=res["coord"]["lon"], lat=res["coord"]["lat"]))), "timestamp": datetime.datetime.now(tz=timezone( tf.timezone_at(lng=res["coord"]["lon"], lat=res["coord"]["lat"]))).strftime( "%A %B %d, %Y %I:%M:%S %p %Z") }) if res.get("name") and res["name"] != None: data.update({"name": res["name"]})
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
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
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/")
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)
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')}.")
def main(city, country): geolocator = Nominatim(user_agent="cityinfogather") tf = TimezoneFinder() city_name = city.strip().capitalize().replace(' ', '+') country_name = country.strip().capitalize() try: country = pycountry.countries.get(name=country_name) loc = geolocator.geocode(city_name+',' + country_name) latitude = loc.latitude longitude = loc.longitude timezone = tf.timezone_at(lng=longitude, lat=latitude) current_time = time(timezone) current_time = current_time.strftime('%Y:%m:%d %H:%M:%S') except: current_time = "Sorry, the Current Time is Not Available :(" try: country_currency = ccy.countryccy(country.alpha_2) exchangerate = exchangerates(country_currency) except: exchangerate = "Sorry, the Exchange Rate is Currently Not Available :(" temperature, feels_like = weather(city_name) return exchangerate, temperature, feels_like, current_time
def time_aware(self): """ Convert datetime unix_epoch(update.message.date) to specifict UTC timezone local, default Asia/Jakarta in parameters construct Return: json_datetime = {'date': aware_date, 'time': aware_time, 'zone': t_zone} format date: 2020-07-30 '%Y-%m-%d' format time: 24:50:00 '%H:%M:%S' format zone: 'continent/city' (str) """ tf = TimezoneFinder() tzone_user = tf.timezone_at(lng=self.longi, lat=self.latit) try: t_utc = utc.localize(self.unix_epoch) t_to_user = t_utc.astimezone(timezone(tzone_user)) fmt_date = '%Y-%m-%d' fmt_time = '%H:%M:%S' fmt_zone = '%z:%Z' aware_time = datetime.strftime(t_to_user, fmt_time) aware_date = datetime.strftime(t_to_user, fmt_date) # t_zone = datetime.strftime(t_to_user, fmt_zone) json_datetime = { 'date': aware_date, 'time': aware_time, 'tzinfo': tzone_user } finish = json.dumps(json_datetime) logger.info(f'Today in datetime USER: {t_to_user}') except UnknownTimeZoneError as e: logger.info("Unknow Timezone: %s", e) return finish
def task_mail(): url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=bdb2fc4dceba425650a3e1fea845179c' tf = TimezoneFinder(in_memory=True) utc = pytz.utc city = 'New York' city_weather = requests.get(url.format(city)).json() #request the API data and convert the JSON to Python data types now_utc = utc.localize(datetime.utcfromtimestamp(city_weather['dt'])) weather = { 'city' : city, 'temperature' : city_weather['main']['temps'], 'description' : city_weather['weather'][0]['description'], 'icon' : city_weather['weather'][0]['icon'], ##'tisme' : datetime.fromtimestamp(city_weather['dt']).strftime('%Y-%m-%d'), 'date' : now_utc.astimezone(timezone(tf.timezone_at(lng=city_weather['coord']['lon'], lat=city_weather['coord']['lat']))).strftime('%Y-%m-%d') } subject = "Today's weather in NYC" message = "Today is " + str(weather["date"])+ ". The weather in " + weather["city"] + " is " + weather["description"] +" with the temperature: " + str(weather["temperature"]) + " °F." mail_sent = send_mail(subject, message, '*****@*****.**', ['*****@*****.**','*****@*****.**']) return mail_sent
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
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
def get_timezone(latitude, longitude): #Get today sunrise and sunset sun = Sun(latitude, longitude) today_sr = int(sun.get_sunrise_time().strftime('%H')) today_ss = int(sun.get_sunset_time().strftime('%H')) #Get timezone tf = TimezoneFinder() timezone = tf.timezone_at(lng=longitude, lat=latitude) # returns 'Europe/Berlin' #Get time tz = pytz.timezone(timezone) timezone_now = int(datetime.datetime.now(tz).strftime('%H')) logging.info(str(timezone_now)) logging.info(str(today_sr)) logging.info(str(today_ss)) if timezone_now > today_sr and timezone_now < today_ss: day = "Day" else: day = "Night" return day
def create(self, validated_data): place = Place(**validated_data) review = GeneralReview() review.save() place.general_review = review try: latitude, longitude = validated_data.get('address').get( 'coordinates') if latitude and longitude: place.timezone = TimezoneFinder().timezone_at(lat=latitude, lng=longitude) except AttributeError: pass place.save() return place
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.gprmc_status = 0 self.gpgga_status = 0 self.lat = 0 self.lon = 0 self.dataline = '' tf = TimezoneFinder() duration = 60 / 2 #minutes rate_gps = 1 self.array_gps = [''] * duration * rate_gps
def getTime(object_input): extracted = object_input.extract_entities() for i in extracted: if i[1] == "GPE": extracted = i[0] geolocator = Nominatim(user_agent="geoapiExercises") location = geolocator.geocode(extracted) result = TimezoneFinder().timezone_at(lng=location.longitude, lat=location.latitude) tz = pytz.timezone(result) timezone_now = datetime.now(tz) return timezone_now.strftime( f"The time in {extracted} is %I:%M %p") now = datetime.now() timeNow = now.strftime("%H:%M") d = datetime.strptime(timeNow, "%H:%M") return (d.strftime(f"The time is %I:%M %p"))
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
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)
def on_chat_message(self, msg): content_type, chat_type, chat_id = telepot.glance(msg) print('Chat:', content_type, chat_type, chat_id) if content_type != 'text': return self.sendMessage(chat_id, self.data['confused_msg'], reply_markup=self.defaultMarkup[self.current_users[chat_id].language]) text = msg['text'].lower() user = self.db.users.find_one({'chat_id':chat_id}) if not chat_id in self.current_users: self.setUser (chat_id, msg['from']) if user: self.current_users[chat_id].mapUser(user) self.current_users[chat_id].reset = False elif not user and self.current_users[chat_id].reset and text not in self.data['start']: return self.restart(chat_id) if text in self.data['start'] or msg['message_id'] == 0: self.current_users[chat_id].reset = True self.current_users[chat_id].language_setting_msg = self.language_setting(chat_id) elif text in self.data['settings']: if not self.current_users[chat_id].reset: markup = ReplyKeyboardMarkup(keyboard=self.keyboard_two_col(self.data['setting_keyboard'][self.current_users[chat_id].language]), resize_keyboard=True, one_time_keyboard=True) text_msg = self.data['setting_msg'][self.current_users[chat_id].language] self.sendMessage(chat_id, text_msg, reply_markup=markup) else: return self.restart(chat_id) elif text in self.data['get_exercise']: self.sendExercise(list(self.db.users.find({'chat_id': chat_id}))) elif text in self.data['get_question']: self.questionGathering(list(self.db.users.find({'chat_id': chat_id}))) elif text in self.data['statistics']: text_msg = {} en_start = "You started to use the service on {:%d, %b %Y}\n".format(user['_id'].generation_time) fi_start = "Aloit käyttää palvelua {:%d, %b %Y}\n".format(user['_id'].generation_time) en_recieved_exercises = "You have recieved {0} exercises.\nYou have done {1} exercises.\nAmong the done exercises, you have trained your:\ncore: {2} times\nlegs: {3} times\narms: {4} times\nhands: {5} times.\nAnd there were:\n{6} stretching exercises\n{7} balance exercises\n{8} strength exercises".format(self.db[str(chat_id)].count(), user['done'], user['core'], user['legs'], user['arms'], user['hands'], user['stretching'], user['balance'], user['strength']) fi_recieved_exercises = "Olet saanut {0} harjoitusta.\nOlet tehnyt {1} harjoitusta.\nTekemäsi harjoitukset ovat treenanneet:\nkeskikroppaa: {2} krt\njalkoja: {3} krt\nkäsivarsia: {4} krt\nkäsiä: {5} krt.\nHarjoitustyypit:\n{6} kpl venyttely\n{7} kpl tasapaino\n{8} kpl voima".format(self.db[str(chat_id)].count(), user['done'], user['core'], user['legs'], user['arms'], user['hands'], user['stretching'], user['balance'], user['strength']) en_goal = "\nYour current goal is: " + user['goals'][0]['en'] fi_goal = "\nTämänhetkinen tavoitteesi on: " + user['goals'][0]['fi'] text_msg['en'] = en_start + en_recieved_exercises + en_goal text_msg['fi'] = fi_start + fi_recieved_exercises + fi_goal self.sendMessage(chat_id, text_msg[self.current_users[chat_id].language], reply_markup=self.defaultMarkup[self.current_users[chat_id].language]) elif text in self.data['new_goal'] or msg['text'] == self.data['checkup_keyboard'][self.current_users[chat_id].language][1]: self.current_users[chat_id].goal_setting_msg = self.goal_setting(chat_id, self.current_users[chat_id].lowerbody_score, self.current_users[chat_id].upperbody_score) elif text in self.data['new_time'] or msg['text'] == self.data['checkup_keyboard'][self.current_users[chat_id].language][2]: self.current_users[chat_id].times_setting_msg = self.times_setting(chat_id) elif text in self.data['new_condition'] or msg['text'] == self.data['checkup_keyboard'][self.current_users[chat_id].language][3]: self.current_users[chat_id].lowerbody_setting_msg = self.lowerbody_setting(chat_id) elif text in self.data['new_language']: self.current_users[chat_id].language_setting_msg = self.language_setting(chat_id) elif text in self.data['new_location']: self.current_users[chat_id].location_setting_msg = self.location_setting(chat_id) elif msg['text'] == self.data['checkup_keyboard'][self.current_users[chat_id].language][0]: text_msg = self.data['checkup_continue_response'][self.current_users[chat_id].language] self.sendMessage(chat_id, text_msg, reply_markup=self.defaultMarkup[self.current_users[chat_id].language]) elif msg['message_id'] - self.current_users[chat_id].language_setting_msg < 5 and text in ['english','finnish']: self.current_users[chat_id].language = text[:2] self.current_users[chat_id].language_setting_msg = -1000 if self.current_users[chat_id].reset: self.current_users[chat_id].location_setting_msg = self.location_setting(chat_id) else: text_msg = self.data['language_response'][text[:2]] self.sendMessage(chat_id, text_msg, reply_markup=self.defaultMarkup[self.current_users[chat_id].language]) self.updateUserDB(chat_id) elif msg['message_id'] - 1 == self.current_users[chat_id].location_setting_msg: g = geocoder.google(text) if len(g.latlng) == 0: text_msg = self.data['location_fail_response'][self.current_users[chat_id].language] self.sendMessage(chat_id, text_msg) self.current_users[chat_id].location_setting_msg = self.location_setting(chat_id) return tf = TimezoneFinder() self.current_users[chat_id].location = [g.latlng[1], g.latlng[0]] point = (g.latlng[1], g.latlng[0]) self.current_users[chat_id].timezone = tf.timezone_at(*point) if self.current_users[chat_id].reset: self.current_users[chat_id].lowerbody_setting_msg = self.lowerbody_setting(chat_id) else: markup = ReplyKeyboardMarkup(keyboard=[ [self.data['time_keyboard'][self.current_users[chat_id].language]], ],resize_keyboard=True,one_time_keyboard=True) text_msg = self.data['location_response'][self.current_users[chat_id].language] self.sendMessage(chat_id, text_msg, reply_markup=markup) self.updateUserDB(chat_id) elif msg['message_id'] - self.current_users[chat_id].lowerbody_setting_msg < 5 and msg['text'] in self.data['lowerbody_keyboard'][self.current_users[chat_id].language]: self.current_users[chat_id].lowerbody_score = self.data['lowerbody_keyboard'][self.current_users[chat_id].language].index(msg['text']) self.current_users[chat_id].lowerbody_setting_msg = -1000 self.current_users[chat_id].upperbody_setting_msg = self.upperbody_setting(chat_id) elif msg['message_id'] - self.current_users[chat_id].upperbody_setting_msg < 5 and msg['text'] in self.data['upperbody_keyboard'][self.current_users[chat_id].language]: self.current_users[chat_id].upperbody_score = self.data['upperbody_keyboard'][self.current_users[chat_id].language].index(msg['text']) self.current_users[chat_id].upperbody_setting_msg = -1000 if self.current_users[chat_id].reset: self.current_users[chat_id].times_setting_msg = self.times_setting(chat_id) else: text_msg = self.data['condition_response'][self.current_users[chat_id].language] self.sendMessage(chat_id, text_msg,reply_markup=self.defaultMarkup[self.current_users[chat_id].language]) self.updateUserDB(chat_id) elif msg['message_id'] - self.current_users[chat_id].times_setting_msg < 5 and text.isdigit(): self.current_users[chat_id].times = int(text) self.current_users[chat_id].times_setting_msg = -1000 self.current_users[chat_id].time_setting_msg = self.time_setting(chat_id) self.current_users[chat_id].timeslots = [] elif msg['message_id'] - self.current_users[chat_id].time_setting_msg < 10: try: naive = datetime.strptime ("2016-4-27 " + msg['text'], "%Y-%m-%d %H:%M") except ValueError: text_msg = self.data['time_fail_response'][self.current_users[chat_id].language] return self.sendMessage(chat_id, text_msg) local = pytz.timezone (self.current_users[chat_id].timezone) local_dt = local.localize(naive, is_dst=None) utc_dt = local_dt.astimezone (pytz.utc) self.current_users[chat_id].timeslots.append(utc_dt.strftime("%H")) if len(self.current_users[chat_id].timeslots) == self.current_users[chat_id].times: self.current_users[chat_id].time_setting_msg = - 1000 if self.current_users[chat_id].reset: self.current_users[chat_id].goal_setting_msg = self.goal_setting(chat_id, self.current_users[chat_id].lowerbody_score, self.current_users[chat_id].upperbody_score) else: text_msg = self.data['time_response'][self.current_users[chat_id].language] self.sendMessage(chat_id, text_msg, reply_markup=self.defaultMarkup[self.current_users[chat_id].language]) self.updateUserDB(chat_id) elif msg['message_id'] - 1 == self.current_users[chat_id].goal_setting_msg: goal = self.db.goals.find_one({self.current_users[chat_id].language: msg['text']}) if not goal: text_msg = self.data['goal_fail_response'][self.current_users[chat_id].language] self.sendMessage(chat_id, text_msg) self.current_users[chat_id].goal_setting_msg = self.goal_setting(chat_id, self.current_users[chat_id].lowerbody_score, self.current_users[chat_id].upperbody_score) return goal['timestamp'] = datetime.now() self.current_users[chat_id].timestamp = datetime.now() self.current_users[chat_id].goals.insert(0,goal) if self.current_users[chat_id].reset: text_msg = self.data['setup_done_response'][self.current_users[chat_id].language] else: text_msg = self.data['goal_response'][self.current_users[chat_id].language] + text self.sendMessage(chat_id, text_msg,reply_markup=self.defaultMarkup[self.current_users[chat_id].language]) self.updateUserDB(chat_id) elif msg['text'] in self.data['exercise_keyboard'][self.current_users[chat_id].language]: exercise = list(self.db[str(chat_id)].find().limit(1).sort([('_id',-1)]))[0] answered_timestamp = datetime.now() if msg['text'] == self.data['exercise_keyboard'][self.current_users[chat_id].language][0]: done = 1 self.db.users.find_one_and_update({'chat_id': chat_id},{ '$inc': { 'strength' : exercise['strength'], 'stretching' : exercise['stretching'], 'balance' : exercise['balance'], 'core' : exercise['core'], 'hands' : exercise['hands'], 'arms' : exercise['arms'], 'legs' : exercise['legs'], 'done' : 1} }) self.sendMessage(chat_id, self.doing_exercise_response(self.current_users[chat_id].language),reply_markup=self.defaultMarkup[self.current_users[chat_id].language]) self.sendMessage(chat_id, self.data['exercise_done_response'][self.current_users[chat_id].language]) else: done = 0 self.sendMessage(chat_id, self.skip_exercise_response(self.current_users[chat_id].language),reply_markup=self.defaultMarkup[self.current_users[chat_id].language]) self.db[str(chat_id)].update_one({'_id': exercise['_id']}, {'$set':{'answered_timestamp': answered_timestamp, 'done': done}}) del self.current_users[chat_id] elif msg['text'] in self.data['question_keyboard'][self.current_users[chat_id].language]: if chat_id in self.users_to_send_msg: answer = {} answer['chat_id'] = chat_id answer['question_content'] = self.users_to_send_msg[chat_id]['question_msg']['text'] answer['answer'] = msg['text'] answer['question_id'] = self.users_to_send_msg[chat_id]['question']['_id'] answer['timestamp'] = datetime.now() self.db.answers.insert_one(answer) del self.users_to_send_msg[chat_id] self.sendMessage(chat_id, self.data['question_resonse'][self.current_users[chat_id].language] + u'\U0001f44d', reply_markup=self.defaultMarkup[self.current_users[chat_id].language]) del self.current_users[chat_id] else: response_msg = self.random_response(text) self.sendMessage(chat_id, response_msg)
else: name = "NO_NAME" # Coordinates gx_track = d.getElementsByTagName('gx:Track')[0] gx_coord_element = gx_track.getElementsByTagName('gx:coord') if gx_coord_element.length > 0: gx_coord = gx_track.getElementsByTagName('gx:coord')[0] coords = gx_coord.firstChild.data.split(' ') longitude = float(coords[0]) latitude = float(coords[1]) else: break #print("longitude:{0}, latitude:{1}".format(longitude, latitude)) # Get timezone of the coordinates # t = datetime.tzinfo("America/New_York") tf = TimezoneFinder() tz = tzwhere.tzwhere(shapely=True) timezone_str = tf.timezone_at(lng=longitude, lat=latitude) # timezone_str = tzwhere.tzNameAt(37.3880961, -5.9823299) #print("timezone of current location: {0}".format(timezone_str)) t = pytz.timezone(timezone_str) # begin and end time of the visiting timespan = d.getElementsByTagName('TimeSpan')[0] begin = timespan.getElementsByTagName('begin')[0].firstChild.data begin_datetime = dateutil.parser.parse(begin).astimezone(t) end = timespan.getElementsByTagName('end')[0].firstChild.data end_datetime = dateutil.parser.parse(end).astimezone(t) begin_date = begin_datetime.date() begin_time = begin_datetime.time() end_date = end_datetime.date() end_time = end_datetime.time()