def init_hook(): weather=Weather() tz = tzwhere.tzwhere() location='Prague' homeloc=getLocation(location) tz = tzwhere.tzwhere() tz_name =tz.tzNameAt(homeloc.latitude,homeloc.longitude) timez = timezone(tz_name) d = datetime.datetime.utcnow() d = timez.localize(d) weather.set_init_parameters(homeloc.latitude,homeloc.longitude,d.utcoffset().seconds/3600) return weather
def init_hook(): weather = Weather() tz = tzwhere.tzwhere() location = 'Prague' homeloc = getLocation(location) tz = tzwhere.tzwhere() tz_name = tz.tzNameAt(homeloc.latitude, homeloc.longitude) timez = timezone(tz_name) d = datetime.datetime.utcnow() d = timez.localize(d) weather.set_init_parameters(homeloc.latitude, homeloc.longitude, d.utcoffset().seconds / 3600) return weather
def __init__(self, options, *args, **kwargs): self.options = options self.args = args self.kwargs = kwargs self.usr = create_observer(get_location(options['-l'])) self.objects = {} usr, objects = self.usr, self.objects # Build user's custom set of objects if options['OBJECTS']: build_objects(options['OBJECTS'], objects, usr) else: # Default objects are solar system planets for candidate in ephem._libastro.builtin_planets(): if candidate[1] == 'Planet' and candidate[2] != 'Sun': objects[candidate[2]] = getattr(ephem, candidate[2])(usr) # Change user's date if specified # TODO: Timezone from user specified location = more expensive-tzwhere? if options['-t']: try: timezone_str = tzwhere.tzwhere().tzNameAt( float(usr.lat * deg_to_rad), float(usr.lon * deg_to_rad)) local_dt = pytz.timezone(timezone_str).localize( dateparser.parse(options['-t'])) print('Timezone is: ' + timezone_str) print('Time set to: ' + local_dt.strftime('%Y-%m-%d %H:%M:%S')) usr.date = local_dt.astimezone(pytz.utc) except: print('Could not interpret date, using local time')
def __init__(self, lat=None, lon=None, tzname="UTC"): if lat is not None and lon is not None: with nostdout(): w = tzwhere.tzwhere() self.tz = timezone(w.tzNameAt(lat, lon)) else: self.tz = timezone(tzname)
def get_time(inputs={'location': ''}): place = '' if not len(inputs.items()) == 0: place = inputs['location'] if place == '': ts = time.time() st = datetime.fromtimestamp(ts).strftime('%I %M %p') tTime = st.split(' ') t = str(int(tTime[0])) + ' ' + tTime[1] + ' ' + tTime[2] return {'time': t} from tzwhere import tzwhere place = place.replace(' ', '+') search_details = 'https://geocoder.api.here.com/6.2/geocode.json?app_id=cb870QP7ugZzb4tWAcKI&app_code=d4xPcsr4E8fj_rzUNhkXgQ&searchtext=' + place resp = requests.get(url=search_details, params='') data = resp.json() tz = tzwhere.tzwhere() lat = data['Response']['View'][0]['Result'][0]['Location'][ 'DisplayPosition']['Latitude'] lon = data['Response']['View'][0]['Result'][0]['Location'][ 'DisplayPosition']['Longitude'] timeZoneStr = tz.tzNameAt(lat, lon) timeZoneObj = timezone(timeZoneStr) ts = datetime.now(timeZoneObj).strftime('%H:%M:%S') return {'time': ts}
def __init__(self, t_0, t_1, sat, topos, earth, sun, visible=True): self.sat_minimum_observable_altitude = 10.0 self.sat_pass_rough_period = 0.0042 # average pass duration of 6 minutes time, _ = almanac.find_discrete( t_0, t_1, self._satellite_pass(sat, topos, earth, sun, visible)) difference = sat - topos self.passes = [] self.pass_types = ['eclipsed', 'visible', 'daylight'] timezone_str = tzwhere.tzwhere().tzNameAt(topos.latitude.degrees, topos.longitude.degrees) for i in range(1, len(time), 2): start_t, end_t = time[i - 1], time[ i] # TODO: check that y[i-1] and not y[i] culm_t, _ = extremum.find_maximum( start_t, end_t, lambda t: difference.at(t).altaz('standard')[0].degrees) _, mag = extremum.find_minimum( start_t, end_t, lambda t: satpred_utilities.apparent_magnitude( sat, topos, earth, sun, t)) if satpred_utilities.civil_twilight( topos, earth, sun, start_t) and satpred_utilities.civil_twilight( topos, earth, sun, end_t): if satpred_utilities.umbral_eclipse( sat, earth, sun, start_t) and satpred_utilities.umbral_eclipse( sat, earth, sun, end_t): pass_type = self.pass_types[0] else: pass_type = self.pass_types[1] else: pass_type = self.pass_types[2] self.passes.append( SatellitePass(sat, topos, timezone_str, start_t, culm_t, end_t, pass_type, np.round(mag, 1)))
def broadcast_pushing_country(country, city): if fk.request.method == 'GET': _country = get_country(country) if _country is None: return service_response(204, 'Unknown country', 'We could not find this country.') else: lat = _country["lat"] lng = _country["lng"] if lat == "": lat = 0.00 lng = 0.00 tz = tzwhere.tzwhere() timeZoneStr = tz.tzNameAt(lat, lng) timeZoneObj = timezone(timeZoneStr) now_time = datetime.datetime.now(timeZoneObj) day = str(now_time).split(" ")[0] date = datetime.datetime.strptime(day, "%Y-%m-%d") if city == "all": broadcast_pulled = Broadcast.objects(country=country, status='pulled', day=day).first() else: broadcast_pulled = Broadcast.objects(city=city.lower(), country=country, status='pulled', day=day).first() if broadcast_pulled: broadcast_pulled.status = 'pushing' broadcast_pulled.save() ignore, language = get_cities(country) broadcast_pushing =broadcast_pulled.info() translator = Translator(to_lang=language) broadcast_pushing["message"] = translator.translate(broadcast_pushing["message"]) return service_response(200, translator.translate('Broadcast in () today {0}:'.format(day)), broadcast_pushing) else: return service_response(204, 'No broadcast to send', "no broadcast at this point.") else: return service_response(405, 'Method not allowed', 'This endpoint supports only a GET method.')
def weather_pushing_country(country, city): if fk.request.method == 'GET': _country = get_country(country) if _country is None: return service_response(204, 'Unknown country', 'We could not find this country.') else: lat = _country["lat"] lng = _country["lng"] if lat == "": lat = 0.00 lng = 0.00 tz = tzwhere.tzwhere() timeZoneStr = tz.tzNameAt(lat, lng) timeZoneObj = timezone(timeZoneStr) now_time = datetime.datetime.now(timeZoneObj) day = str(now_time).split(" ")[0] date = datetime.datetime.strptime(day, "%Y-%m-%d") next_date = date + datetime.timedelta(days=1) next_day = datetime.datetime.strftime(next_date, "%Y-%m-%d") weather_pulled = Weather.objects(city=city.lower(), country=country, status='pulled', day=next_day).first() if weather_pulled: weather_pulled.status = 'pushing' weather_pulled.save() ignore, language = get_cities(country) weather_pushing = weather_pulled.info() translator = Translator(to_lang=language) return service_response(200, translator.translate('Weather in () tomorrow {0}:'.format(next_day)), weather_pushing) else: return service_response(204, 'No weather to send', "no weather at this point.") else: return service_response(405, 'Method not allowed', 'This endpoint supports only a GET method.')
def post_facebook_message_new(fbid, message_text): post_message_url = 'https://graph.facebook.com/v2.6/me/messages?access_token=%s' % PAGE_ACCESS_TOKEN geolocation = Nominatim() location = geolocation.geocode(message_text or "nyc") address = str(location.address) latitude = int(location.latitude) longitude = int(location.longitude) tz = tzwhere.tzwhere() time_zone = tz.tzNameAt(latitude, longitude) now = datetime.now(pytz.timezone(time_zone)) fmt = "Date: %d-%m-%Y\nTime: %H:%M:%S" output_text = "*********\n" + now.strftime( fmt ) + "\n*********" + "\nlocation:" + address + "\n" + time_zone + " " + str( latitude) + "," + str(longitude) response_msg = json.dumps({ "recipient": { "id": fbid }, "message": { "text": output_text } }) status = requests.post(post_message_url, headers={"Content-Type": "application/json"}, data=response_msg)
def broadcast_today_city(country, city): if fk.request.method == 'GET': _country = get_country(country) if _country is None: return service_response(204, 'Unknown country', 'We could not find this country.') else: lat = _country["lat"] lng = _country["lng"] if lat == "": lat = 0.00 lng = 0.00 tz = tzwhere.tzwhere() timeZoneStr = tz.tzNameAt(lat, lng) timeZoneObj = timezone(timeZoneStr) now_time = datetime.datetime.now(timeZoneObj) day = str(now_time).split(" ")[0] if city == 'all': if country == 'all': broadcasts = [c.info() for c in Broadcast.objects(day=day)] else: broadcasts = [c.info() for c in Broadcast.objects(day=day, country=country)] else: broadcasts = [c.info() for c in Broadcast.objects(day=day, city=city.lower(), country=country)] return service_response(200, 'City: {0} of Country: {1} broadcast today: {2}'.format(city.lower(), country, day), {'size':len(broadcasts), 'today':broadcasts}) else: return service_response(405, 'Method not allowed', 'This endpoint supports only a GET method.')
def find_tz(INFILE, OUTFILE_IN, OUTFILE_OUT): """ Inputs: infile: name of input csv file. outfile: name of output csv file. Assumes that the columns are date/time (in GTN-P standard format), then latitude (as a signed decimal number, where North is positive), then longitude (as a signed decimal number, where East is positive) """ header = True for infile, outfile in zip(INFILE.iter_contents(), OUTFILE_IN.iter_contents()): with open(infile, newline='') as _in, open(outfile, 'w', newline='') as out: data = csv.reader(_in) output = csv.writer(_out) finder = tzwhere.tzwhere() for line in data: if (header): output.writerow(line + ['UTC Offset']) header = False else: coord = (float(line[1]), float(line[2])) tzname = finder.tzNameAt(*coord) tm = time.strptime(line[0].strip(), '%Y-%m-%d %H:%M') dt = datetime.datetime(tm.tm_year, tm.tm_mon, tm.tm_mday, tm.tm_hour, tm.tm_min) offset = name_to_offset(tzname, dt) output.writerow(line + [offset])
def find_timezone(lat, long): tz = tzwhere.tzwhere() timezone_str = tz.tzNameAt(lat, long) #print(timezone_str) local_timezone = pytz.timezone(timezone_str) return local_timezone
def _get_training_data(db, prev_model_timestamp): """ Get data that will be used to updatimport pandase the prediction model. Only data collected from previous model update are collected, unless `prev_model_timestamp` is set to None :param gpudb.GPUdb db: Kinetica DB connection :param int prev_model_timestamp: Timestamp of previous model update. Set to None to get all data in the DB :returns: (X, y) tuple where X is a DataFrame containing training samples and y is an array of target values :rtype: (pandas.DataFrame, numpy.ndarray) """ tzfinder = tzwhere.tzwhere() events = _get_events_from_db(db, prev_model_timestamp) if len(events['column_1']) == 0: return [], [] events_df = _events_to_dataframe(events) events_df['timezone'] = events_df.apply(lambda e: tzfinder.tzNameAt(e['lat'], e['lon']), axis=1) events_df.dropna(inplace=True) events_df['timezone'] = events_df.apply(lambda e: pytz.timezone(e['timezone']), axis=1) events_df['time_local'] = events_df.apply(lambda e: e['time_utc'].astimezone(e['timezone']), axis=1) events_df['day_of_week'] = events_df.apply(lambda e: e['time_local'].weekday(), axis=1) events_df['hour'] = events_df.apply(lambda e: e['time_local'].hour, axis=1) y = events_df['yes_responses'].values X = events_df return X, y
def nominatim_attempt(): print 'I am using geolocator!!!!!' geolocator = Nominatim() print items[idx]['timezone'] if geolocator.geocode(items[idx]['timezone']) != None: location = geolocator.geocode( items[idx]['timezone']) tz = tzwhere.tzwhere(forceTZ=True) current_location = tz.tzNameAt( location.latitude, location.longitude) timezone = pytz.timezone(current_location) current_date = datetime.strptime( items[idx]['created_at'], '%Y-%m-%dT%H:%M:%SZ') localized_time = pytz.utc.localize( current_date, is_dst=None).astimezone(timezone) time_list.append(localized_time) if items[idx][ 'timezone'] not in timezones_aux_list: format_timezone(items[idx], str(timezone)) timezones_file.write( json.dumps(current_timezone)) timezones_file.write('\n') timezones_aux_list.append( items[idx]['timezone']) global count count += 1 #print 'Processed ' + str(count) + ' items successfully!' else: print 'passing on ' + items[idx]['timezone'] pass
def get_location(message): print('location', message.chat.id) ## # Берем временную зону пользователя. ## tz = tzwhere.tzwhere() timezone_str = tz.tzNameAt(message.location.latitude, message.location.longitude) timezone = pytz.timezone(timezone_str) #print(timezone, timezone.utcoffset(datetime.datetime.now())) timezone_offset = str(timezone.utcoffset(datetime.datetime.now())) self.mongo.coll.update({"id": message.chat.id}, { "$set": { "latitude": message.location.latitude, "longitude": message.location.longitude, "timezone_offset": timezone_offset } }) self.bot.send_message( message.from_user.id, "Ваше местоположение и временная зона: {} {}".format( timezone_str, timezone_offset))
def get_timezone_description(lat, long): tz = tzwhere.tzwhere() location = tz.tzNameAt(lat, long) if type(location) == str: return location else: raise ValueError
def handle_location(message): headers = {"Content-Type": "application/json"} att_url = attendances_url % subject_id lat = message.location.latitude lng = message.location.longitude zone = tzwhere.tzwhere() timezone_str = zone.tzNameAt(lat, lng) timezone = pytz.timezone(timezone_str) time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') payload = { "first_name": message.chat.first_name, "last_name": message.chat.last_name, "longitude": lng, "latitude": lat, "created_at": time } r = requests.post(att_url, headers=headers, data=json.dumps(payload)) if (r.status_code == 403): bot.send_message( message.chat.id, "Ваши координаты: {0}, {1}. Проверка местоположения неуспешна. Вы не в зоне радиуса. Попробуйте подойти к центру аудитории и заново пройти проверку." .format(lat, lng)) elif (r.status_code == 201): bot.send_message( message.chat.id, "Ваши координаты: {0}, {1}. Проверка местоположения успешно пройдена." .format(lat, lng))
def sun(location_in_dd): """(tuple of float) -> tuple of datetime object Takes a tuple of decimal coordinates, returns a tuple of local time now (of radio station) sunrise and sunset.""" rise_set = requests.get("https://api.sunrise-sunset.org/json?lat=" + str(location_in_dd[0]) \ + "&lng=" + str(location_in_dd[1]) + "&date=today&formatted=0") soup = BeautifulSoup(rise_set.content, "html.parser") #use json to decode json file from API to a dict result = json.loads(str(soup)) sunrise = result["results"]["sunrise"] sunset = result["results"]["sunset"] sunrise = sunrise[:10] + " " + sunrise[11:19] sunset = sunset[:10] + " " + sunset[11:19] # get time zone and local time time_zone = tzwhere.tzwhere().tzNameAt(location_in_dd[0], location_in_dd[1]) from_zone = tz.gettz("UTC") to_zone = tz.gettz(time_zone) now = datetime.now(to_zone).time() rise_utc = datetime.strptime(sunrise, "%Y-%m-%d %H:%M:%S") rise_local = rise_utc.replace(tzinfo=from_zone).astimezone(to_zone).time() set_utc = datetime.strptime(sunset, "%Y-%m-%d %H:%M:%S") set_local = set_utc.replace(tzinfo=from_zone).astimezone(to_zone).time() result = (now, rise_local, set_local) return result
def predict_model(path, timestamp): # preparing data and importing model centroids = pd.read_csv(join(sys.path[0], path, file_cluster_centroids), sep=",", header=None).to_numpy() model = keras.models.load_model(join(sys.path[0], path, folder_name)) # determine user's timezone home = pd.read_csv(join(sys.path[0], path, file_home_cluster), sep=',', header=None).to_numpy() tz = tzwhere.tzwhere() timezone_str = pytz.timezone(tz.tzNameAt(home[0], home[1])) # predict and receive list of confidences p = model.predict(extract_single(timestamp, timezone_str)) points = sorted([{ 'latitude': str(lat), 'longitude': str(long), 'radius': str(r), 'confidence': str(conf) } for lat, long, r, conf in zip(centroids[:, 0], centroids[:, 1], centroids[:, 2], p.reshape(p.shape[1]))], key=lambda x: x['confidence'], reverse=True) return points
def __init__(self): self.server_lat = 45.589 self.server_lng = -122.59 # Example format: 2016-08-25T17:27:45.556703+00:00 self.tz = tzwhere.tzwhere(shapely=False) self.timeformat = 'YYYY-MM-DDTHH:mm:ss.SSSSSSZZ' self.server_tz = self.tz.tzNameAt(self.server_lat, self.server_lng)
def __init__(self, right_hand_traffic=True, derive_missing_velocities=True, correct_timezone=False, left_right_is_swapped=False, case_is_left=True): self.derive_missing_velocities = derive_missing_velocities self.correct_timezone = correct_timezone self.left_is_overtaker_side = left_right_is_swapped != right_hand_traffic self.case_is_overtaker_side = case_is_left == right_hand_traffic self.reject_measurements_before = datetime.datetime( 2018, 1, 1, tzinfo=datetime.timezone.utc) self.measurement_template = { 'time': None, 'latitude': None, 'longitude': None, 'distance_overtaker': None, 'distance_stationary': None, 'confirmed': None, 'course': None, 'speed': None, 'in_privacy_zone': None } if self.correct_timezone: self.timezone_lookup = tzwhere.tzwhere(forceTZ=False)
def location_receive(message): if message.location: tzw = tzwhere.tzwhere() timezone_str = tzw.tzNameAt(message.location.latitude, message.location.longitude) user = User.get(message.chat.id) user.timezone = timezone_str user.save() ru_text = f'Часовой пояс изменён на *{timezone_str}*' en_text = f'Timezone changed to *{timezone_str}*' text = ru_text if user.language_code == 'ru' else en_text bot.send_message(message.chat.id, text, reply_markup=markups.get_main_menu_markup( message.chat.id), parse_mode='Markdown') elif message.text == 'Указать вручную': bot.send_message(message.chat.id, 'Выбери свой часовой пояс', reply_markup=markups.get_timezone_markup()) bot.register_next_step_handler(message, timezone_receive) elif message.text == 'Specify manually': bot.send_message(message.chat.id, 'Choose your timezone', reply_markup=markups.get_timezone_markup()) bot.register_next_step_handler(message, timezone_receive) else: bot.register_next_step_handler(message, location_receive)
def __init__(self, ndata=-32767, geonames_usrname=None): ''' Parameters ---------- ndata : int, optional The value that should be returned if no time zone information can be found for the point of interest. geonames_usrname : str, optional A geonames username. If a geonames username is provided, the Geonames web service will be checked for time zone information if no information on a point's time zone can be found via the local shapefile. ''' print "Initializing tzwhere..." self.tzw = tzwhere(shapely=True, forceTZ=True) self.tz_offsets = {} tz_names = np.array(self.tzw.timezoneNamesToPolygons.keys()) tz_names = tz_names[tz_names != 'uninhabited'] a_date = datetime(2009, 1, 1) for a_name in tz_names: a_tz = pytz.timezone(a_name) self.tz_offsets[a_name] = a_tz.utcoffset( a_date).total_seconds() / 3600.0 if geonames_usrname is None: self.tz_geon = None else: self.tz_geon = TZGeonamesClient(geonames_usrname) self.ndata = ndata
def get_local_datetime(self, df): """Short summary. Parameters ---------- df : type Description of parameter `df`. Returns ------- type Description of returned object. """ import pytz from numpy import unique from tzwhere import tzwhere tz = tzwhere.tzwhere(forceTZ=True, shapely=True) df.dropna(subset=['Latitude', 'Longitude'], inplace=True) lons, index = unique(df.Longitude.values, return_index=True) lats = df.Latitude.values[index] dates = df.datetime.values[index].astype('M8[s]').astype('O') df['utcoffset'] = 0 for i, j, d in zip(lons, lats, dates): l = tz.tzNameAt(j, i, forceTZ=True) timezone = pytz.timezone(l) n = d.replace(tzinfo=pytz.UTC) r = d.replace(tzinfo=timezone) rdst = timezone.normalize(r) offset = (rdst.utcoffset()).total_seconds() // 3600 df['utcoffset'].loc[df.Longitude == i] = offset df['datetime_local'] = df.datetime + pd.to_timedelta(df.utcoffset, 'H') return df
def location_response(bot, update): tzw = tzwhere.tzwhere() latitude = update.message.body.attachments[0].latitude longitude = update.message.body.attachments[0].longitude timezone_str = tzw.tzNameAt(latitude, longitude) user = User.get(update.user_id) user.timezone = timezone_str user.save()
def hours_from_utc(lat, lon): tzwh = tzwhere.tzwhere() timezone_str = tzwh.tzNameAt(lat, lon) # Seville coordinates timezone_now = pytz.timezone(timezone_str) utc_hours = datetime.datetime.now( timezone_now).utcoffset().total_seconds() / 60 / 60 return utc_hours
def scan_timezones(outfile, attr_in, *, loutf=False): # Include functions from CAMxtools.write.wrt_ioapi import wrt_ioapi from CAMxtools.write.wrt_uamiv import wrt_uamiv from CAMxtools._cnvt._data2fin import _data2fin from tzwhere import tzwhere # Get nx, ny, dxy, and lcc nx = attr_in['NCOLS'] ny = attr_in['NROWS'] dxy = float(attr_in['XCELL']) # Simply assume XCELL = YCELL lcc = get_lcc(attr_in) # Global variables related to timezone # timezone lookup, force nearest tz for coords outside of polygons #global WHERETZ WHERETZ = tzwhere.tzwhere() # daylight savings time (DST) in northern hemisphere starts in March and ends # in November and the opposite in southern hemisphere #global JAN1 JAN1 = datetime.datetime( 2016, 1, 1) # date with standard time in northern hemisphere #global JUN1 JUN1 = datetime.datetime( 2016, 6, 1) # date with standard time in southern hemisphere # Calculating timezones over the domain print("Calculating timezones over the domain") # If tz is set to auto, calculate a tshift array before the loop tzone_ji = np.zeros((ny, nx)).astype(int) # PST:-8 MST:-7 CST:-6 EST:-5 for i in range(nx): for j in range(ny): lat, lon = proj_latlon_single(i, j, dxy, lcc) tzone_ji[j, i], tz_info = tz_latlon( lat, lon, WHERETZ, JAN1, JUN1) #tz_cell is based on LST not LDT. for itz in (np.unique(-tzone_ji)): print("time zone = {}".format(itz)) # Data array preparation nspc = 1 nz = 1 nsteps = 1 data2sav = np.zeros((nspc, nsteps, nz, ny, nx)) data2sav[0, 0, 0, :, :] = -tzone_ji tracernames = "TZONE".split() # Write output to a binary file fout = _data2fin(data2sav, tracernames, attr_in) l2uam = False # Force to output to IOAPI format if loutf: # Write output to netcdf if l2uam: wrt_uamiv(outfile, fout) else: wrt_ioapi(outfile, fout) else: return tracernames, data2sav
def tzw(self): if TimeZones._tzw is None: print "Initializing tzwhere for time zone retrieval...", TimeZones._tzw = tzwhere(shapely=True, forceTZ=True) print 'done.' return TimeZones._tzw
def tzw(self): if TimeZones._tzw is None: print("Initializing tzwhere for time zone retrieval..."), TimeZones._tzw = tzwhere(shapely=True, forceTZ=True) print('done.') return TimeZones._tzw
def get_timezone_and_utc_offset(lat, lon): tz = tzwhere.tzwhere(forceTZ=True) #TODO: This library takes 2 seconds to initialize. Should be done only once if used for many videos timezone_str = tz.tzNameAt(lat, lon) if timezone_str is not None: timezone = pytz.timezone(timezone_str) dt = datetime.datetime.utcnow() return [timezone_str, timezone.utcoffset(dt)] else: print("ERROR: Could not determine timezone") return [None, None]
def check_speed_his_algor(): start_time = datetime.now() tz_where = tzwhere() end_time = datetime.now() tz_where.tzNameAt(latitude=13.3, longitude=53.2) return end_time - start_time
def which_time_zone(ground_position_lat, ground_position_lon): '''which_time_zone takes a gps coord and returns the timezone it falls in. Contact: [email protected] ''' # check the lat and lons to be sensible. futs.check_for_sensible_lat_long([ground_position_lat, ground_position_lon]) tz = tzwhere.tzwhere() return tz.tzNameAt(ground_position_lat, ground_position_lon)
def get_timezone(latitude, longitude): """Get pytz timezone object given latitude and longitude.""" tzw = tzwhere.tzwhere(forceTZ=True) return pytz.timezone( tzw.tzNameAt( latitude=latitude, longitude=longitude, forceTZ=True, ) )
def findTimezones(user_name, file_name, file_name_s): geolocator = GeoNames(username=user_name) g = geocoders.GeoNames(username=user_name) location_index = 0 lat_index = 1 lon_index = 2 res = [] data = [] HOUR = 60 * (60 + 4) utc = pytz.utc utc.zone dat = csv.reader(open(file_name)) w = tzwhere.tzwhere() i = 0 for row in dat: if i > 0: data.append([row[location_index], row[lat_index], row[lon_index]]) i = i + 1 csv_writer = csv.writer(open(file_name_s, 'wb')) #print "number of rows: ", len(data) csv_writer.writerow(HEADER2) for row in data: if (row[lat_index] <> '0' and row[lon_index] <> '0'): lat = float(row[lat_index]) lon = float(row[lon_index]) timezone = w.tzNameAt(lat, lon) print lat print lon print timezone try: country_info = reverceGeoCode([row[lat_index], row[lon_index]], g, geolocator, user_name) except GeocoderServiceError: print "hourly limit has been exceeded, time to wait for an hour..." time.sleep(HOUR) print "starting again..." country_info = reverceGeoCode([row[lat_index], row[lon_index]], g, geolocator, user_name) try: time_diff = timeDifference(utc, timezone) except AttributeError: time_diff = 0 print timezone temp = [ row[location_index], row[lat_index], row[lon_index], timezone, time_diff, country_info[2], country_info[3], country_info[4] ] else: temp = row + [0, 0, 0, 0, 0] res.append(temp) try: csv_writer.writerow(temp) except UnicodeEncodeError: csv_writer.writerow(row + [0, 0, 0, 0, 0]) return res
def __init__(self, lat, lon, name): self.topos = Topos(lat, lon) self.lat = lat self.lon = lon self.ephemeris = load('de430.bsp') self.location = self.ephemeris['earth'] + self.topos self.ts = load.timescale() self.name = name lat_value, lon_value = ll_string_to_float(lat), ll_string_to_float(lon) self.timezone = pytz.timezone(tzwhere.tzwhere().tzNameAt( lat_value, lon_value))
def apply_time(input, output): tz = tzwhere.tzwhere() df = pd.read_csv('xxx.csv') df['tzone'] = df[['lat','lon']].apply(lambda x: tz.tzNameAt(x['lat'], x['lon']), axis=1) df.fillna(value='Australia/Sydney',inplace=True) df['offset'] = df[['tzone']].apply(lambda x: datetime.datetime.now(pytz.timezone(x['tzone'])).strftime('%z'), axis=1) df.to_csv(output)
def find_timezone(lat, lon): """ Search for timezone with geographic coordinates using tzwhere. :param lat: latitude <float> :param lon: longitude <float> :return: timezone in format 'Europe/Paris' <string> """ tz = tzwhere.tzwhere() timezone = tz.tzNameAt(lat, lon) if not timezone: timezone = tz.tzNameAt(round(lat), round(lon)) return timezone
def loadDB(): global conn global cur global tz # 1384210800000 # Just add this in here tz = tzwhere.tzwhere(shapely=True, forceTZ=True) conn = pymysql.connect( host=MYSQL_HOST, port=MYSQL_PORT, user=MYSQL_USER, passwd=MYSQL_PASSWORD, db="mysql", charset="utf8" ) cur = conn.cursor(pymysql.cursors.DictCursor) cur.execute("USE trucking")
def get_timezone_and_utc_offset(lat, lon): #TODO Importing inside function because tzwhere is a temporary solution and dependency fails to install on windows from tzwhere import tzwhere tz = tzwhere.tzwhere(forceTZ=True) #TODO: This library takes 2 seconds to initialize. Should be done only once if used for many videos timezone_str = tz.tzNameAt(lat, lon) if timezone_str is not None: timezone = pytz.timezone(timezone_str) dt = datetime.datetime.utcnow() return [timezone_str, timezone.utcoffset(dt)] else: print("ERROR: Could not determine timezone") return [None, None]
def findTimezones(user_name, file_name, file_name_s): geolocator = GeoNames(username=user_name) g = geocoders.GeoNames(username=user_name) location_index = 0 lat_index = 1 lon_index = 2 res = [] data = [] HOUR = 60 * (60 + 4) utc = pytz.utc utc.zone dat = csv.reader(open(file_name)) w = tzwhere.tzwhere() i = 0 for row in dat: if i>0: data.append([row[location_index], row[lat_index], row[lon_index]]) i = i + 1 csv_writer = csv.writer(open(file_name_s, 'wb')) #print "number of rows: ", len(data) csv_writer.writerow(HEADER2) for row in data: if (row[lat_index] <> '0' and row[lon_index] <> '0'): lat = float(row[lat_index]) lon = float(row[lon_index]) timezone = w.tzNameAt(lat, lon) print lat print lon print timezone try: country_info = reverceGeoCode([row[lat_index], row[lon_index]], g, geolocator, user_name) except GeocoderServiceError: print "hourly limit has been exceeded, time to wait for an hour..." time.sleep(HOUR) print "starting again..." country_info = reverceGeoCode([row[lat_index], row[lon_index]], g, geolocator, user_name) try: time_diff = timeDifference(utc, timezone) except AttributeError: time_diff = 0 print timezone temp = [row[location_index], row[lat_index], row[lon_index], timezone, time_diff, country_info[2], country_info[3], country_info[4]] else: temp = row + [0,0,0,0,0] res.append(temp) try: csv_writer.writerow(temp) except UnicodeEncodeError: csv_writer.writerow(row + [0,0,0,0,0]) return res
def _test_tzwhere(self, locations, forceTZ): start = datetime.datetime.now() w = tzwhere.tzwhere(forceTZ=forceTZ) end = datetime.datetime.now() print('Initialized in: '), print(end - start) template = '{0:20s} | {1:20s} | {2:20s} | {3:2s}' print(template.format('LOCATION', 'EXPECTED', 'COMPUTED', '==')) for (lat, lon, loc, expected) in locations: computed = w.tzNameAt(float(lat), float(lon), forceTZ=forceTZ) ok = 'OK' if computed == expected else 'XX' print(template.format(loc, str(expected), str(computed), ok)) assert computed == expected
def _test_tzwhere(self, input_kind, path): start = datetime.datetime.now() w = tzwhere.tzwhere(input_kind, path) end = datetime.datetime.now() print('Initialized in: '), print(end - start) template = '{0:20s} | {1:20s} | {2:20s} | {3:2s}' print(template.format('LOCATION', 'EXPECTED', 'COMPUTED', '==')) TEST_LOCATIONS = ( ( 35.295953, -89.662186, 'Arlington, TN', 'America/Chicago'), ( 33.58, -85.85, 'Memphis, TN', 'America/Chicago'), ( 61.17, -150.02, 'Anchorage, AK', 'America/Anchorage'), ( 44.12, -123.22, 'Eugene, OR', 'America/Los_Angeles'), ( 42.652647, -73.756371, 'Albany, NY', 'America/New_York'), ( 55.743749, 37.6207923, 'Moscow', 'Europe/Moscow'), ( 34.104255, -118.4055591, 'Los Angeles', 'America/Los_Angeles'), ( 55.743749, 37.6207923, 'Moscow', 'Europe/Moscow'), ( 39.194991, -106.8294024, 'Aspen, Colorado', 'America/Denver'), ( 50.438114, 30.5179595, 'Kiev', 'Europe/Kiev'), ( 12.936873, 77.6909136, 'Jogupalya', 'Asia/Kolkata'), ( 38.889144, -77.0398235, 'Washington DC', 'America/New_York'), ( 59.932490, 30.3164291, 'St Petersburg', 'Europe/Moscow'), ( 50.300624, 127.559166, 'Blagoveshchensk', 'Asia/Yakutsk'), ( 42.439370, -71.0700416, 'Boston', 'America/New_York'), ( 41.84937, -87.6611995, 'Chicago', 'America/Chicago'), ( 28.626873, -81.7584514, 'Orlando', 'America/New_York'), ( 47.610615, -122.3324847, 'Seattle', 'America/Los_Angeles'), ( 51.499990, -0.1353549, 'London', 'Europe/London'), ( 51.256241, -0.8186531, 'Church Crookham', 'Europe/London'), ( 51.292215, -0.8002638, 'Fleet', 'Europe/London'), ( 48.868743, 2.3237586, 'Paris', 'Europe/Paris'), ( 22.158114, 113.5504603, 'Macau', 'Asia/Macau'), ( 56.833123, 60.6097054, 'Russia', 'Asia/Yekaterinburg'), ( 60.887496, 26.6375756, 'Salo', 'Europe/Helsinki'), ( 52.799992, -1.8524408, 'Staffordshire', 'Europe/London'), ( 5.016666, 115.0666667, 'Muara', 'Asia/Brunei'), (-41.466666, -72.95, 'Puerto Montt seaport', 'America/Santiago'), ( 34.566666, 33.0333333, 'Akrotiri seaport', 'Asia/Nicosia'), ( 37.466666, 126.6166667, 'Inchon seaport', 'Asia/Seoul'), ( 42.8, 132.8833333, 'Nakhodka seaport', 'Asia/Vladivostok'), ( 50.26, -5.051, 'Truro', 'Europe/London'), ( 50.26, -8.051, 'Sea off Cornwall', None) ) for (lat, lon, loc, expected) in TEST_LOCATIONS: computed = w.tzNameAt(float(lat), float(lon)) ok = 'OK' if computed == expected else 'XX' print(template.format(loc, str(expected), str(computed), ok)) assert computed == expected
def listing_to_json(flight_nr, asset_path): # read yaml try: filename = "img_listings/ubseds{}.markdown".format(flight_nr) images = read_yaml_from_markdown(filename)["images"] config_filename = "img_listings/ubseds{}_config.yaml".format(flight_nr) config = read_yaml(config_filename) except: # failed to read listing return None js_obj = [] # takes some time to initialise print("Initialising timezones...") tz = tzwhere.tzwhere(shapely=True, forceTZ=True) for img in images: try: location = parse_exif_gps(img["GPSPosition"], img["GPSAltitude"]) human_time = parse_datetime(img["ModifyDate"], tz, location) js_obj.append({ 'name': img['name'], 'location': location, 'human_time': human_time }) except: None # uhh just ignore bad images # write json config["json"] = asset_path + "img.json" json_filename = "../.." + asset_path + "img.json" with open(json_filename, "w") as outfile: json.dump(js_obj, outfile, indent=2) return { 'config': config, 'images': js_obj }
def home(request): """ Default view for the root """ try: profile = UserProfile.objects.get(user=request.user) except UserProfile.DoesNotExist: profile = UserProfile.objects.create( user = request.user ) checkins = CheckIn.objects.order_by('-time')[:10] saved_current_time = datetime.now(profile.current_timezone).strftime("%Y-%m-%d %H:%M:%S") ip = get_real_ip(request) if os.getenv('IP_OVERRIDE'): ip = os.getenv('IP_OVERRIDE') if ip is None: ip = current_location = None current_timezone = current_time = current_location = 'Unknown' else: geoip = GeoIP() tzw = tzwhere.tzwhere() location_info = geoip.city(ip) if location_info is None: ip = current_location = None current_timezone = current_time = current_location = 'Unknown' else: current_location = location_info['city'] current_timezone = pytz.timezone(tzw.tzNameAt(*geoip.lat_lon(ip))) current_time = datetime.now(current_timezone).strftime("%Y-%m-%d %H:%M:%S") return render(request, 'checkin/home.html', { 'profile': profile, 'checkins': checkins, 'saved_current_time': saved_current_time, 'current_location': current_location, 'current_timezone': current_timezone, 'current_time': current_time, })
def doAction(self,r,sr,words,sensorList): if self.tz == None: os.system("espeak -s 120 'loading solar data'") self.tz = tzwhere.tzwhere() fix = sensorList["location"].getLastData() if fix["lastFix"] == None: return "I don't know where you are" l = Location() l.name = 'gpsFix' l.region = 'gpsFix' l.latitude = float(fix["lastFix"]["lat"]) l.longitude = float(fix["lastFix"]["lon"]) l.timezone = self.tz.tzNameAt(float(fix["lastFix"]["lat"]),float(fix["lastFix"]["lon"])) l.elevation = float(fix["lastFix"]["alt"]) if "sunset" in words: return str(l.sunset().strftime("%-I:%M%P")) if "sunrise" in words: return str(l.sunrise().strftime("%-I:%M%P")) if "phase of the moon" in words: return str(l.moon_phase())
def populate_img_datetime_obj_local(self,w=None): ## Get the time/date at the image collect location logger.debug('') logger.debug('Adding self.img_datetime_obj_local to obj data members.') logger.debug('') try: self.img_tz = w.tzNameAt(self.meta.latlonhae[0], self.meta.latlonhae[1]) except: ### # Loading a tzwhere intstance from scratch... # This could be theoretically changed by including a ' # timezone database or a module that wraps one instead of ' # the json file.' ### #logger.debug('') logger.debug('Opening a tzwhere instance for access to the json file. ' 'This is slow! You can pass in a pregenerated instance ' 'of the json database to the variable w in order to speed ' 'up the processing of multiple images. This is done by ' 'importing tzwhere using "from tzwhere import tzwhere" and ' 'then creating the instance using "w=tzwhere.tzwhere()" ' 'See notes in code for possible development to improve ' 'speed if needed.') logger.debug('') w = tzwhere.tzwhere() self.meta.img_tz = w.tzNameAt( self.meta.latlonhae[0], self.meta.latlonhae[1]) if not self.meta.img_tz: logger.debug('') logger.debug('No time zone code returned, this location may be in ' 'the middle of the ocean. Defaulting to a simple ' 'latitude based time zone calculation.') offset = self._calc_gmtoffset(self.meta.latlonhae[1]) #print offset self.meta.img_tz = 'Etc/GMT' + str(offset) tzinfo_img = pytz.timezone(self.meta.img_tz) self.meta.img_datetime_obj_local = \ self.meta.img_datetime_obj_utc.astimezone(tzinfo_img)
""" Tools for PVSC-44 Clearysky AOD Analysis """ from datetime import datetime import pytz from tzwhere import tzwhere # timezone lookup, force nearest tz for coords outside of polygons WHERETZ = tzwhere.tzwhere(shapely=True, forceTZ=True) # daylight savings time (DST) in northern hemisphere starts in March and ends # in November and the opposite in southern hemisphere JAN1 = datetime(2015, 1, 1) # date with standard time in northern hemisphere JUN1 = datetime(2015, 6, 1) # date with standard time in southern hemisphere def tz_latlon(lat, lon): """ Timezone from latitude and longitude. :param lat: latitude [deg] :type lat: float :param lon: longitude [deg] :type lon: float :return: timezone :rtype: float """ # get name of time zone using tzwhere, force to nearest tz tz_name = WHERETZ.tzNameAt(lat, lon, forceTZ=True) # check if coordinates are over international waters
def __init__(self, lat, lon): with nostdout(): w = tzwhere.tzwhere() self.tz = timezone(w.tzNameAt(lat, lon))
import csv import calendar import itertools import dropbox from datetime import datetime,timedelta from pytz import timezone from itertools import chain,imap from tzwhere.tzwhere import tzwhere from os import path import time from xml.dom.minidom import parseString months = dict((month,num) for num,month in enumerate(calendar.month_name)) namer = tzwhere() def delocalize_time(timestring, latitude, longitude): # Given: a lat, long coordinate and timestamp in its local time # Result: the time converted to UTC tzname = namer.tzNameAt(float(latitude), float(longitude)) try: tz = timezone(tzname) except AttributeError: return None dt = datetime.strptime(timestring, "%Y-%m-%dT%H:%M:%SZ") dt = tz.localize(dt) dt = dt.astimezone(timezone('UTC')) time = dt.strftime('%Y-%m-%dT%H:%M:%S') return time def fetch_gps(conf):
#!/usr/bin/python import os, time from gps import * from tzwhere import tzwhere from Adafruit_LED_Backpack import SevenSegment gpsd= gps(mode = WATCH_ENABLE) print "Acquiring gps fix..." while gpsd.fix.mode != MODE_3D: gpsd.next() time.sleep(1) tz = tzwhere.tzwhere() tzname = tz.tzNameAt(gpsd.fix.latitude, gpsd.fix.longitude) print "Setting timezone to " + tzname os.environ['TZ'] = tzname time.tzset() # Create display instance on default I2C address (0x70) and bus number. display = SevenSegment.SevenSegment(busnum=2) display.begin() while True: localtime = time.localtime(time.time()) timestr = time.strftime('%I') + time.strftime('%M') display.clear() display.set_colon(localtime[5] % 2) display.print_number_str(timestr) display.write_display()
from tzwhere import tzwhere tz = tzwhere.tzwhere(input_kind='csv') def benchmark(): for i in range(10000): tz.tzNameAt(35.29, -89.66) import cProfile cProfile.run('benchmark()')
import requests import json from geopy import geocoders from tzwhere import tzwhere from pytz import timezone import pytz def getlocation(linkIn): requested = requests.get(linkIn) userinfo = json.loads(requested.text) location = userinfo["location"] return location username = '******' firstlink = 'https://api.github.com/users/'+username thecity = getlocation(firstlink) g = geocoders.GoogleV3() place, (lat,lng) = g.geocode(thecity) print place print (lat, lng) w = tzwhere.tzwhere() print w.tzNameAt(lat, lng)
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() #print("Begin date: {0}, Begin time: {1}, End date: {2}, End time: {3}".format(begin_date, begin_time,end_date, end_time))
"""timezone Logic.""" import arrow from tzwhere.tzwhere import tzwhere print('Loading tzwhere... ', end='') TZ_FINDER = tzwhere() print('done.') def get_current_server_time(): """Return the current time in the server's timezone.""" return arrow.now() def get_timezone_for(lat_lng): """Find the timezone at a location. >>> get_timezone_for((35.29, -89.66)) 'America/Chicago' """ lat, lng = lat_lng return TZ_FINDER.tzNameAt(lat, lng) def translate_time_to_location(time, lat_lng): """Return a given time in the timezone at a location. >>> translate_time_to_location( ... arrow.get('2016-08-25T10:40:15-07:00'), ... (35.29, -89.66)
def get_timezone_from_geo(lat, lon): """ Return String TimeZone from provided lat,lon """ tz = tzwhere.tzwhere() return tz.tzNameAt(float(lat), float(lon))
from dateutil.parser import parse import pytz import geocoder import swisseph as swe swe.set_ephe_path('/usr/share/libswe/ephe/') from django.utils.translation import ugettext_lazy as _ from django.utils.translation import pgettext_lazy from django.db import models from timezone_field import TimeZoneField from tzwhere.tzwhere import tzwhere from users.models import UserProfile tzwhere = tzwhere() class Event(models.Model): user = models.ForeignKey(UserProfile, related_name='events', null=True, verbose_name=_('User')) name = models.CharField(max_length=256, verbose_name=_('Name')) date = models.DateTimeField(verbose_name=_('Date')) city = models.CharField(max_length=256, verbose_name=_('City')) location = models.ForeignKey('Location', related_name='events', null=True, verbose_name=_('Location')) ephemeris = models.OneToOneField('Ephemeris', related_name='event', verbose_name=_('Events')) houses = models.OneToOneField('Houses', related_name='event', verbose_name=_('Houses')) class Meta: verbose_name = _('event') verbose_name_plural = _('events') def __unicode__(self): return self.name
from rest_framework.decorators import api_view from observation.conditions import Forecast from observation.api.models import MapSeries from rest_framework import serializers from rest_framework.renderers import JSONRenderer from observation.conditions import ForecastConditions from observation.conditions.utils import next_update from geopy import geocoders from dateutil import tz from tzwhere.tzwhere import tzwhere tzlookup = tzwhere() import json import hashlib from django.core.cache import get_cache try: geocode_cache = get_cache('geocode') except: geocode_cache = get_cache('default') try: coverage_cache = get_cache('coverage') except: coverage_cache = get_cache('default')
def computeValueAdded(self, minyr=1950, maxyr=2014, vbose=0): ''' Compute the "Value Added" variables. for games table: - playoff_flag - year_id for events table: - playoff_flag - year_id - time_since_1900 : an integer giving the number of seconds since Jan 1, 1900, UTC - tto : times through the order - sun_alt, sun_az : altitude and azimuth of the sun - woba_pts : woba_pts for the event - woba_pts_expected : placeholder for woba_pts expected from the matchup of batter vs pitcher. ''' if self.guts is None: self.guts = self.readFgGutsJson() if self.seamheads is None: self.seamheads = self.getSeamheadsParksData() aptz = {} tzw = tzwhere.tzwhere() sun = ephem.Sun() aa_total_events = self.getEventCount() pflags = {} q = 'select a.*, b.event_id, b.event_cd, b.bat_id, b.pit_id, b.bat_lineup_id from (select game_id, start_game_tm, minutes_game_ct, park_id, daynight_park_cd, cast(substr(game_id, 4, 4) as unsigned) as year_id, cast(substr(game_id, 8, 2) as unsigned) as mn_id, cast(substr(game_id, 10, 2) as unsigned) as day_id from %s) a inner join %s b on a.game_id=b.game_id where a.year_id>=%d and a.year_id<=%d ' % (self.TABLE_NAMES['TBL_RETRO_GAMES'], self.TABLE_NAMES['TBL_RETRO_EVENTS'], minyr, maxyr) if vbose>=1: print q data = self.sqlQueryToArray(q) rdata = {} rdata['TBL_RETRO_GAMES'] = [] rdata['TBL_RETRO_EVENTS'] = [] aTTO = {} for d in data: mval = {} if vbose>=1: print d gid = d['game_id'] pid = d['pit_id'] bl = d['bat_lineup_id'] ev_id = d['event_id'] ev_cd = d['event_cd'] yr = int(gid[3:3+4]) mn = int(gid[7:7+2]) dy = int(gid[9:9+2]) if not yr in pflags: pflags[yr] = self.makePlayoffFlag(yr)['gids'] mval['year_id'] = yr mval['playoff_flag'] = pflags[yr][gid] park = d['park_id'] lat = float(self.seamheads[park]['Latitude']) lon = float(self.seamheads[park]['Longitude']) elev = float(self.seamheads[park]['Altitude']) if not park in aptz: aptz[park] = tzw.tzNameAt(lat, lon) tz = aptz[park] tzi = pytz.timezone(tz) dt = d['minutes_game_ct'] st = d['start_game_tm'] shrs = st/100 smins = st-100*(st/100) if shrs<9: shrs += 12 tstart = datetime.datetime(yr, mn, dy, shrs, smins, 0, 0) x = datetime.timedelta(0,int(dt*60)) tend = tstart + x dn = (1.0*dt)/aa_total_events[gid] t0 = datetime.datetime(1900, 1, 1, 0, 0, 0) t0 = tzi.localize(t0).astimezone(pytz.utc) if dt>0: obs = ephem.Observer() if vbose>=1: print 'dn', dn, 'ev_id', ev_id x = datetime.timedelta(0,np.floor(dn*(ev_id-1)*60)) blah = tzi.localize(tstart + x).astimezone(pytz.utc) obs.date = blah sun.compute(obs) x_1900 = (blah-t0).days*86400 + (blah-t0).seconds obs.lat = lat*self.deg2rad obs.long = lon*self.deg2rad obs.elev = elev mval['sun_alt'] = float(sun.alt)*self.rad2deg mval['sun_az'] = float(sun.az)*self.rad2deg mval['time_since_1900'] = x_1900 k = '%s_%s' % (gid, pid) if not k in aTTO: aTTO[k] = {} if not bl in aTTO[k]: aTTO[k][bl] = 0 aTTO[k][bl] += 1 mval['tto'] = aTTO[k][bl] if not gid in self.eventUpdateData: self.eventUpdateData[gid] = {} self.eventUpdateData[gid][ev_id] = {} self.eventUpdateData[gid][ev_id]['tto'] = aTTO[k][bl] woba_pts = self.getEventWoba(ev_cd, yr, vbose=vbose) if not woba_pts is None: self.eventUpdateData[gid][ev_id]['woba_pts'] = woba_pts mval['woba_pts'] = woba_pts if vbose>=1: print gid, ev_id, ev_cd, yr, aTTO[k][bl], aa_total_events[gid] tmp = {} mval['game_id'] = gid mval['event_id'] = ev_id rdata['TBL_RETRO_GAMES'].append({'game_id' : mval['game_id'], 'playoff_flag' : mval['playoff_flag'], 'year_id' : mval['year_id']}) rdata['TBL_RETRO_EVENTS'].append(mval) return rdata
import pytz utc = pytz.utc def take(n, iterable): "Return first n items of the iterable as a list" return list(islice(iterable, n)) def get_tweetlocal(tweet): dt = tweet['created_at'] tz = z.tzNameAt(tweet['coordinates'][1], tweet['coordinates'][0]) # Note, we are still returning UTC time. return utc.localize(dt), tz db = twitterproj.connect() z = tzwhere() county_shp = '../tiger/tl_2014_us_county.shp' class JobManager(twitterproj.JobManager): def parent(self): with fiona.open(county_shp, 'r') as f: for i, feature in enumerate(f): self.launch_child(i, feature, wait=60) def child(self, job_id, feature): state_fips = feature['properties']['STATEFP'] county_fips = feature['properties']['COUNTYFP'] geoid = feature['properties']['GEOID'] name = feature['properties']['NAMELSAD'] mapping = us.states.mapping('fips', 'name')
import pytz from datetime import datetime from TwitterGeoPics.Geocoder import Geocoder from tzwhere import tzwhere GEO = Geocoder() TZ = tzwhere.tzwhere() def compare_timezone(latitude, longitude, utc_offset): """The trick: Does longitude fall within timezone?""" try: tz_name = TZ.tzNameAt(latitude, longitude) if not tz_name: return False military = datetime.now(pytz.timezone(tz_name)).strftime('%z') hours = int(military[:(len(military)-2)]) minutes = int(military[-2:]) seconds = (abs(hours)*60 + minutes)*60 except Exception as e: # logging.error('COMPARE TIME ZONE ERROR: %s' % e) return False test = abs(seconds - abs(utc_offset)) <= 3600 #strict_test = abs(hours/abs(hours)*seconds - utc_offset) <= 3600 return test def update_geocode(status): """Get geocode from tweet's 'coordinates' field (unlikely) or from tweet's location and Google.""" if 'geocoder' in status: