def get_time_zone(lat: float, lon: float) -> pytz.tzinfo: timezone_str = timezonefinder.TimezoneFinder().certain_timezone_at(lat=lat, lng=lon) if timezone_str is None: raise ValueError("Could not determine the time zone") else: return pytz.timezone(timezone_str)
def check_global_forced(ds, chk, messages): forced = chk["Global"]["Forced"] ds_global = ds.globalattributes # force global attributes that have defined values for item in forced: if item not in ds_global: msg = "Global: " + item + " not found in global attributes" messages["ERROR"].append(msg) continue else: if ds_global[item] != forced[item]: msg = "Global: " + item + " (" + ds_global[ item] + "), should be " + forced[item] messages["ERROR"].append(msg) # and do the time zone lon = float(ds_global["longitude"]) lat = float(ds_global["latitude"]) tf = timezonefinder.TimezoneFinder() time_zone = tf.timezone_at(lng=lon, lat=lat) if "time_zone" in ds_global: if ds_global["time_zone"] != time_zone: msg = "Global: existing time zone (" + ds_global[ "time_zone"] + ") doesn't match " + time_zone messages["ERROR"].append(msg) else: pass else: ds_global["time_zone"] = time_zone return
def __init__(self, lat, lon, panel_tilt=20, session_id=None, ip_or_url='192.168.15.7', port=27017): # Date/wall time attributes if session_id == None: import uuid self.session_id = uuid.uuid1() self.a = Astral() self.timezone_string = 'US/Pacific' # Timezone from lat/lng tzfinder = timezonefinder.TimezoneFinder() self.tz = tzfinder.certain_timezone_at(lat=lat, lng=lon) self.location = Location(('Burlingame', 'Pacific West', lat, lon, self.timezone_string, 6.1)) self.sun = self.location.sun(date=dt.datetime.today().date(), local=True) print(self.sun) # MongoDB Tracking self.mongo_client = MongoClient(ip_or_url, port) self.db = self.mongo_client.astral # Tilt of theoretical panel self.tilt = math.radians(panel_tilt)
def time_zone(self): # get timezone tz = _tzf.TimezoneFinder() tz_str = tz.timezone_at(lng = self.lon, lat = self.lat) now = _datetime.datetime.now(_pytz.timezone(tz_str)) tz_hr = now.utcoffset() / _datetime.timedelta(hours = 1) return tz_str, tz_hr
def get_timezone_str(lat, lng): tf = timezonefinder.TimezoneFinder() timezone_str = tf.certain_timezone_at(lat=lat, lng=lng) if timezone_str is None: timezone_str = "Pacific/Auckland" return timezone_str
def get_forecast(self, lat=45.523, lng=-73.581, days=4): owm = OWM(owm_key) self.lat = lat self.lng = lng self.days = days #if we want to use current weather if days == 0: fc = owm.weather_at_coords(self.lat, self.lng) w = fc.get_weather() self.T = w.get_temperature('celsius')['temp'] self.rain = 1 if not w.get_rain() else 0 self.forecast = (self.T, self.rain) #if we want to use weather forecast else: #Get weather forecast over the next five days, at 3h intervals fc = owm.three_hours_forecast_at_coords(self.lat, self.lng) #Get tempreature forecast and weather status at 12h and 15h (local time) over the next four days #Get the timezone tf = timezonefinder.TimezoneFinder() timezone_str = tf.certain_timezone_at(lat=self.lat, lng=self.lng) #Get the current local time self.clt = datetime.now() #Create a list of local times for which we want a forecast forecast_wanted = [ self.clt + timedelta(days=i) for i in range(1, self.days + 1) ] list_of_forecast_wanted = [i.replace(hour=12) for i in forecast_wanted] + \ [i.replace(hour=15) for i in forecast_wanted] #Change from local time to utc tmz = timezone(timezone_str) list_of_forecast_wanted = [ tmz.localize(i).astimezone(timezone('UTC')) for i in list_of_forecast_wanted ] #Get the temperature forecast and average temperature temperature_forecast = [ fc.get_weather_at(i).get_temperature('celsius')['temp'] for i in list_of_forecast_wanted ] self.average_forecasted_T = np.mean(temperature_forecast) #See if it forecasts rain or not (0-->no rain, 1-->rain) rain_forecast = [ 1 if fc.will_be_rainy_at(i) else 0 for i in list_of_forecast_wanted ] self.rain = 1 if float( np.sum(rain_forecast)) / len(rain_forecast) >= 0.5 else 0 self.forecast = (self.average_forecasted_T, self.rain)
def addtimezone(lat, lon): try: import timezonefinder tf = timezonefinder.TimezoneFinder() return (lat, lon, tf.timezone_at(lng=float(lon), lat=float(lat))) #return (lat, lon, 'America/Los_Angeles') # FIXME except ValueError: return (lat, lon, 'TIMEZONE') # header
def _add_timezone(self, lat_str, lng_str): lng = float(lng_str) lat = float(lat_str) import timezonefinder tfinder = timezonefinder.TimezoneFinder() tzone = tfinder.timezone_at(lng=lng, lat=lat) if tzone is None: tzone = 'UTC' return (lat_str, lng_str, tzone)
def addtimezone(lat, lon): try: import timezonefinder tf = timezonefinder.TimezoneFinder() lat = float(lat) lon = float(lon) return lat, lon, tf.timezone_at(lng=lon, lat=lat) except ValueError: return lat, lon, 'TIMEZONE' # header
def lat_lon_to_timezone(point: Point) -> tz.tz.tzfile: """ Looks up the time zone of a lat-lon and returns a timezone instance """ lat = point.y lon = point.x tf = timezonefinder.TimezoneFinder() tz_str = tf.certain_timezone_at(lat=lat, lng=lon) return tz.gettz(tz_str)
def addtimezone(lat, lon): try: import timezonefinder tf = timezonefinder.TimezoneFinder() tz = tf.timezone_at(lng=float(lon), lat=float(lat)) if tz is None: tz = 'UTC' return (lat, lon, tz) except ValueError: return (lat, lon, 'TIMEZONE') # header
def time_adjuster(lat, lon): # Get timezone string for coordinates # Example: crd = [40.17759, -112.45244] returns 'America/Denver' loc = timezonefinder.TimezoneFinder().timezone_at(lat=lat, lng=lon) # Dummy date to get time offset date = datetime.datetime(year=1970, month=1, day=1, hour=0, minute=0) tz = pytz.timezone(loc) # Note: Arizona doesn't observe DST, so Arizona locations may experience timeshifts of 1 hour utc_offset = tz.utcoffset(date, is_dst=True) return utc_offset
def __init__(self, lat, lon, panel_tilt=20, razonIP="192.168.15.150"): # Config Settings latitude = math.radians(lat) longitude = math.radians(lon) self.tilt = math.radians(panel_tilt) dzenith = latitude-panel_tilt self.razonIP = razonIP # Timezone from lat/lng tzfinder = timezonefinder.TimezoneFinder() self.tz = tzfinder.certain_timezone_at(lat=lat, lng=lon)
def time_zone_basic(): tf = timezonefinder.TimezoneFinder() timezone_str = tf.certain_timezone_at(lat=49.2827, lng=-123.1207) if timezone_str is None: print "Could not determine the time zone" else: timezone = pytz.timezone(timezone_str) date_str = "2014-05-28 22:28:15" dt = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S") print dt print "The time in %s is %s" % (timezone_str, dt + timezone.utcoffset(dt))
def timezone_execute(): tf = timezonefinder.TimezoneFinder() filename = 'Temple.txt' temples = pd.read_csv(filename, delimiter='\t', header=None) lat_coords = temples.values[:, 3] long_coords = temples.values[:, 4] # long is negative in the US all_results = [] for index in range(len(lat_coords)): result = tf.timezone_at(lng=long_coords[index], lat=lat_coords[index]) all_results.append(result) with open('timezones.json', 'w') as filename: json.dump(all_results, filename)
def correct_timezone(dt_value, latitude, longitude): ''' Applies timezone correction to a date-time object using latitude and longitude information ''' latitude, longitude = float(latitude), float(longitude) tf = timezonefinder.TimezoneFinder() timezone_str = tf.certain_timezone_at(lat=latitude, lng=longitude) if timezone_str is None: tz_corrected = dt_value else: timezone = pytz.timezone(timezone_str) tz_corrected = dt_value + timezone.utcoffset(dt_value) return tz_corrected
def parseDate_withTimeZone(date_date, lat, lon): # ClientGMaps=gmaps.Client(RESTApi.objects.get(name='googleMapsRESTApi').APIKey) # dict_location={ # "lat" : lat, # "lng" : lon, # } # dict_timezone=ClientGMaps.timezone(dict_location) tf = timezonefinder.TimezoneFinder() timezone_str = tf.certain_timezone_at(lat=lat, lng=lon) date_date = date_date.astimezone(timezone(timezone_str)) return date_date
def __init__(self, ax, lat, lng, cmap, prop): """ """ print('Creating Solar Path Diagram.') self.cmap = plt.get_cmap(cmap) self.prop = prop self.ax = ax self.year = datetime.datetime.now().year self.lat = lat self.lng = lng tf = timezonefinder.TimezoneFinder() self.time_zone = pytz.timezone(tf.certain_timezone_at(lng=lng, lat=lat)) self.plot_solar_path()
def observer(self): """Return an `astroplan.Observer` representing an observer at this facility, accounting for the latitude, longitude, elevation, and local time zone of the observatory (if ground based).""" try: return self._observer except AttributeError: tf = timezonefinder.TimezoneFinder(in_memory=True) local_tz = tf.closest_timezone_at( lng=self.lon, lat=self.lat, delta_degree=5 ) self._observer = astroplan.Observer( longitude=self.lon * u.deg, latitude=self.lat * u.deg, elevation=self.elevation * u.m, timezone=local_tz, ) return self._observer
def theoryExecute(): stime = request.args['stime'] etime = request.args['etime'] stime = datetime.strptime(stime, "%H:%M:%S").time() etime = datetime.strptime(etime, "%H:%M:%S").time() result = [] try: conn = db.connect(DB_CONNECTION_STRING) cursor = conn.cursor() sql = '''SELECT "n_time", "latitude", "longitude" FROM QUAKES''' cursor.execute(sql, ) result = cursor.fetchall() conn.close() except: result.append("error try again") count = [0, 0] i = 0 for r in result[:]: print i i += 1 tf = timezonefinder.TimezoneFinder() if r[1] <= -90 or r[1] >= 90: continue if r[2] <= -180 or r[2] >= 180: continue timezone_str = tf.certain_timezone_at(lat=r[1], lng=r[2]) if timezone_str is None: print "Could not determine the time zone" else: timezone = pytz.timezone(timezone_str) local_time = ((r[0] + timezone.utcoffset(r[0])).time()) if stime < local_time < etime: count[0] += 1 continue count[1] += 1 print count return render_template('theory.html', count=count)
def check_special_intent(intent, res_nlp, language): message = None # Case: weather if intent == "get-weather": location = res_nlp['nlp']['entities'].get('location')[0] if res_nlp['nlp']['entities'].get('location') else res_nlp['conversation']['memory'].get('weather-location') if location: latitude = location['lat'] longitude = location['lng'] if not latitude and not longitude: return CUSTOM_MESSAGES[language]['no-weather'] if res_nlp['nlp']['entities'].get('datetime'): time = int(dp.parse(res_nlp['nlp']['entities']['datetime'][0]['iso']).strftime('%s')) else: time = int(t.time()) print('{}, {}, {}, {}'.format(latitude, longitude, time, language)) res = get_weather(latitude, longitude, time, language) tf = timezonefinder.TimezoneFinder() current_tz = tz.gettz(tf.timezone_at(lng=longitude, lat=latitude)) local_time = datetime.fromtimestamp(time).replace(tzinfo=current_tz) if language == 'fr': message = 'La météo pour {} le {}: {} avec une temperature de {} °C et une probabilité de précipitation de {}%' else: message = 'The weather for {} at {}: {} with a temperature of {} °C with a probability of raining of {}%' message = message.format( location['formatted'], local_time.strftime("%d/%m/%Y à %Hh%M"), res['currently']['summary'], res['currently']['temperature'], res['currently']['precipProbability']) if intent == "cryptonews": if res_nlp['nlp']['entities'].get('cryptomonnaie'): crypto = res_nlp['nlp']['entities']['cryptomonnaie'][0]['value'] print(crypto) res, found = get_crypto(crypto) if not found: message = CUSTOM_MESSAGES[language]['resource-not-found'] else: if language == 'fr': message = 'La cryptomonnaie {0} vaut actuellement {1:.2f} € et a évolué de {2:.2f} % depuis les dernières 24h.' else: message = 'The cryptocurrency {0} is actually at {1:.2f} € and changed of {2:.2f} % during the last 24 hours.' message = message.format( crypto, res['value'], res['evolution']) if intent == "news": res = get_news() message = res['message'] return message
def add_clock(self, inp): con = inp.get() tz = next((c for c in countries.countries if c['name'].lower() == con.lower()), None) if not tz is None: self.default[con] = tz['timezones'][0] elif tz is None: geolocator = geopy.geocoders.Nominatim(user_agent="timeapp") location = geolocator.geocode(con.lower()) latitude, longitude = (location.latitude, location.longitude) tf = timezonefinder.TimezoneFinder() tz = tf.timezone_at(lng=longitude, lat=latitude) self.default[con] = tz inp.delete(0, tk.END) with open('./tzcache.py', 'w') as file: file.write('cache = ') json.dump(self.default, file) self.default_clocks(1, 2)
def set_tolarance(start='06:00:00', end='23:00:00', main=1, secondary=5): start = datetime.datetime.strptime(start, '%H:%M:%S') end = datetime.datetime.strptime(end, '%H:%M:%S') #Adjust timezone tf = timezonefinder.TimezoneFinder() timezone_str = tf.certain_timezone_at(lat=g.latlng[0], lng=g.latlng[1]) timezone = pytz.timezone(timezone_str) dt = datetime.datetime.utcnow() timezone.localize(dt) now = datetime.datetime.utcnow() + timezone.utcoffset(dt) # compare current time to start and end points if now > start and now < end: if light.get( ) == 0: # Check if the lights are on. Indicates if someone is active. return main else: return secondary else: return main
def __init__(self, name, interface=None, event=None, clock=None, latLong=None, tz=None): Interface.__init__(self, name, interface, event) self.clock = None # interface: optional gps location data file if interface: self.clock = "gps" import timezonefinder self.timeZoneFinder = timezonefinder.TimezoneFinder() # clock: time source # local - system clock is local tz (default) # utc - system clock is UTC # gps - gps time via file interface if clock: self.clock = clock else: if not self.clock: self.clock = "local" # latLong: location coordinates as tuple(lat, long) if latLong: self.latLong = latLong else: self.latLong = (0, 0) # tz: time zone in Olson format (e.g. "America/Los_Angeles") if tz: self.tz = tz else: if self.clock == "local": # local TZ if clock is local self.tz = '/'.join( os.readlink('/etc/localtime').split('/')[-2:]) else: self.tz = "UTC" debug('debugTime', self.name, "clock:", self.clock, "latLong:", self.latLong, "tz:", self.tz)
def get_time(self, inp, time_text, city_text): con = inp.get() tz = next((c for c in countries.countries if c['name'].lower() == con.lower()), None) if not tz is None: # Clock(self.window, pytz.timezone(tz['timezones'][0]), 7, 1, con) d = datetime.now(pytz.timezone(tz['timezones'][0])) time_text.set(d.strftime('%H:%M:%S')) city_text.set(con) elif tz is None: time_text.set('Please enter a valid name!') geolocator = geopy.geocoders.Nominatim(user_agent="timeapp") location = geolocator.geocode(con.lower()) latitude, longitude = (location.latitude, location.longitude) tf = timezonefinder.TimezoneFinder() tz = tf.timezone_at(lng=longitude, lat=latitude) d = datetime.now(pytz.timezone(tz)) time_text.set(d.strftime('%H:%M:%S')) city_text.set(con) # Clock(self.window, pytz.timezone(tz), 7, 1, con) inp.delete(0, tk.END)
def __init__(self, lat, lng, cloud_data, cmap, prop): """ """ print('Creating Solar Irradiance Plot.') self.cmap = plt.get_cmap(cmap) self.prop = prop tf = timezonefinder.TimezoneFinder() self.time_zone = pytz.timezone(tf.certain_timezone_at(lng=lng, lat=lat)) date_rng = pd.date_range( start='1/1/{}'.format(datetime.datetime.now().year), end='1/1/{}'.format(datetime.datetime.now().year + 1), freq='H', tz=self.time_zone)[:-1] alts = get_altitude_fast(lat, lng, date_rng.values) irradiances = np.array([ get_radiation_direct(date, alt) if alt > 0 else 0 for date, alt in zip(date_rng, alts) ]) irr = pd.DataFrame({ 'Month': date_rng.month, 'Day': date_rng.day, 'irradiance': irradiances }) irr_by_day = irr.groupby(['Month', 'Day']).irradiance.sum() / 1000.0 irr = pd.DataFrame({ 'Mean': irr_by_day.groupby('Month').mean(), 'Std': irr_by_day.groupby('Month').std() }) self.irr = irr self.clouds = cloud_data.clouds
def __init__( self, longitude: float, latitude: float, datetime, ): super().__init__(longitude, latitude, datetime) self.name = "Solar System bodies visibility" self.observer = ephem.Observer() # datetime must be in UTC!!! self.observer.date = str(datetime) # lat and lon must be converted to strings to make pyephem recognize them # as degrees, not radians self.observer.lat = str(latitude) self.observer.lon = str(longitude) tf = timezonefinder.TimezoneFinder() tz_str = tf.timezone_at(lng=longitude, lat=latitude) self.timezone = pytz.timezone(tz_str) self.local_datetime = datetime.astimezone(self.timezone)
def observer_timezone(self): """Return an `astroplan.Observer` representing an observer at this facility, accounting for the latitude, longitude, elevation, and local time zone of the observatory (if ground based).""" try: return self._observer_timezone except AttributeError: if (self.lon is None or self.lon == "" or np.isnan(self.lon) or self.lat is None or self.lat == "" or np.isnan(self.lat) or self.fixed_location is False or self.fixed_location is None): self._observer_timezone = None return self._observer_timezone try: tf = timezonefinder.TimezoneFinder(in_memory=True) local_tz = tf.timezone_at(lng=(self.lon + 180) % 360 - 180, lat=self.lat) elevation = self.elevation # if elevation is not specified, assume it is 0 if (self.elevation is None or self.elevation == "" or np.isnan(self.elevation)): elevation = 0 self._observer_timezone = astroplan.Observer( longitude=self.lon * u.deg, latitude=self.lat * u.deg, elevation=elevation * u.m, timezone=local_tz, ) except Exception as e: log(f'Telescope {self.id} ("{self.name}") cannot calculate an observer: {e}' ) self._observer_timezone = None return self._observer_timezone
def time_arr(year: int, lon: float, lat: float, use_dst: bool = True) -> np.ndarray: # determine timezone based on lon, lat tz_str = timezonefinder.TimezoneFinder().certain_timezone_at(lat=lat, lng=lon) tz = pytz.timezone(tz_str) # generate local start and end times # localize with derived time zone start_time = pd.to_datetime(datetime(year, 1, 1)) end_time = pd.to_datetime(datetime(year, 12, 31, 23, 59)) if use_dst: # generate times times = pd.date_range(start_time, end_time, freq='min') \ .tz_localize(tz, ambiguous=True, nonexistent=timedelta(days=1)) else: # convert to UTC to capture offset start_time = start_time.tz_localize(tz).tz_convert('UTC') end_time = end_time.tz_localize(tz).tz_convert('UTC') # generate times times = pd.date_range(start_time, end_time, freq='min') # convert to UTC then python datetime objects in numpy array return times.tz_convert('UTC').to_pydatetime()
import pyowm import time import datetime import pytz import timezonefinder from geopy.geocoders import Nominatim from t import key, geokey owm = pyowm.OWM(key(), language='ru') geolocator = Nominatim(user_agent=geokey()) tf = timezonefinder.TimezoneFinder() tm = {'1': 'Утром', '2': 'Днем', '3': 'Вечером', '4': 'Ночью'} def wind(deg): if (deg > 337.5): return 'С' elif (deg > 292.5): return 'СЗ' elif (deg > 247.5): return 'З' elif (deg > 202.5): return 'ЮЗ' elif (deg > 157.5): return 'Ю' elif (deg > 122.5): return 'ЮВ' elif (deg > 67.5): return 'В' elif (deg > 22.5):