Coder Social home page Coder Social logo

jannikmi / timezonefinder Goto Github PK

View Code? Open in Web Editor NEW
437.0 10.0 41.0 270.46 MB

python package for finding the timezone of any point on earth (coordinates) offline

Home Page: https://timezonefinder.michelfe.it/

License: MIT License

Python 94.81% Shell 1.70% Makefile 1.53% C 1.96%
timezone coordinates latitude longitude python geolocation timezone-picker timezones location timezone-library

timezonefinder's Introduction

Hi there 👋🏻

I am Jannik, a data scientist with a strong background in Python, hyperparameter optimisation and scientific computing.

I love to design and implement efficient algorithms especially in abstract domains.

My other interests include: AGI, computational geometry, knowledge representation and reasoning, machine and reinforment learning.

With my open source projects I want to give back to the community I owe so much to.

You can contact me on LinkedIn or buy me a coffee.

timezonefinder's People

Contributors

adamchainz avatar arimallick avatar dannynemer avatar dependabot[bot] avatar dollars avatar gunyarakun avatar jannikmi avatar joshuadavidthomas avatar josteinl avatar mourishitz avatar navignaw avatar ringsaturn avatar sefiotonomo avatar synapticarbors avatar tirkarthi avatar tmdean avatar ty1776 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

timezonefinder's Issues

Optimize closest_timezone_at()

Make algorithm work when closest polygon is on the 'other end of earth'.
Until now polygons across the +-180deg longitude border are not being considered.
To support this, the distances would need to be computed differently.

Optimize closest_timezone_at() 2

Don't check every coordinate of the possible polygons, but rather preselect them.
(The computation of the distance from one line section of a polygon is quite complicated)

I had the idea to only select the sequence of points in the polygon which actually face the input point, but I did not come up with a valid algorithm for this (since polygons could be of various shapes and too complicated algorithms might take away the benefit of optimization)

At first i wanted to just look for the points with the most extreme phase (angle) from the input point, but then I realized that the polygon may surround the point and the phase might overflow ( e.g. from > pi to <pi). So this approach did not work.

Wrong timezone guess in China

With the following coordinates: 42.88783N 93.63952E, located in China (https://www.openstreetmap.org/?mlat=42.88783&mlon=93.63918#map=5/42.88783/93.63918), using:

from timezonefinder import TimezoneFinder
from pytz import timezone
import pytz
from datetime import datetime, timedelta

utc = pytz.utc
tf = TimezoneFinder()

def get_timezone_offset(lat, lon):
    """
      returns the supposed offset from UTC in hour.
      Stolen from https://github.com/MrMinimal64/timezonefinder
    """
    today = datetime.now()
    tz_target = timezone(tf.certain_timezone_at(lat=lat, lng=lon))
    today_target = tz_target.localize(today)
    today_utc = utc.localize(today)
    return (today_utc - today_target).total_seconds() / 3600

The following code returns 6.0 while calling:

>>> get_timezone_offset(42.88783, 93.63952)
6.0

the expected result is 8.0, since China is in the same timezone (GMT+8) for the whole country, relying on https://www.timeanddate.com/time/map/

Tested with timezonefinder v3.0.1

[info] Command line

Hi,
Is it possible to run this program directly from a command line (bash prompt)?
Something like:
python timezonefinder.py lat=45 lon=-1
Best,
Chris

Using ahead of time compilation

Make use of the pycc feature of Numba:
http://numba.pydata.org/numba-doc/latest/user/pycc.html

It would be ideal if the helper functions were compiled on installation on the user's system once (when Numba is installed). This would probably speed up the algorithms.

I encountered the issue that on my system the produced (compiled) code is for the wrong target architecture and hence cannot be run.

I would be glad if someone else could tell me if they are encountering the same issues.

A draft for how this could work is already included in the latest version of timezonefinder.
Procedure would be:

  • uncomment the compilation code in helpers_numba.py
  • uncomment the import code in timezonefinder.py
  • use timezonefinder (then you should get notifications if it worked or not)

RuntimeWarning: overflow encountered in long_scalars - trying to figure out why

I'm trying to track down a potential issue (either with my own code base (more likely) or the library (less likely)). When running unit tests on a Django application that makes use of the timezonefinder library, I'm getting the following warning printed out:

C:\Python27\lib\site-packages\timezonefinder\helpers.py:42: RuntimeWarning: overflow encountered in long_scalars
  if (x1GEx and x2GEx) or ((x1GEx or x2GEx) and (y2 - y) * (x2 - x1) >= (y2 - y1) * (x2 - x)):

My first thought is that I was somehow passing it bad data, which would seem logical given the warning - if you pass a really large value for y (or x), it could result in an overflow. That makes sense. But what doesn't make sense it it seems almost non-deterministic. If I put a single six.print() statement inside helpers.py, just before that statement, the warning goes away. I am at a bit of a loss as to why this would change anything. Is the six library somehow changing precision of something? Is there any way to tell the timezonefinder library to run using more bits to get around this?

certain_timezone_at fails for small pocket in Saskatchewan

For some reason certain_timezone_at() fails for a small location in the middle of Saskatchewan on version 2.1.2. This can be recreated with the following snippet:

from timezonefinder import TimezoneFinder
tf = TimezoneFinder()
tf.certain_timezone_at(lat=53.0742, lng=-108.9086) # Returns none.  Should return u'America/Regina'

closest_timezone_at works for this location, so we were able to fall back to that, but for some reason that particular latitude/longitude fail. Given that Saskatchewan is basically a giant rectangle, this caught me off guard. Is this perhaps an issue with the underlying data? It shouldn't be anywhere near a coastline, so that shouldn't be an issue.

[v4.0.0] ModuleNotFoundError: No module named 'importlib_resources'

Looks like there might be a missing dependency in v4.0.0. Just importing the package throws a ModuleNotFoundError for importlib_resources

Steps to reproduce:

  1. pip install timezonefinder
  2. Open an interactive python shell
  3. Type from timezonefinder import TimezoneFinder
  4. Observe ModuleNotFoundError

Add conda badge to readme

.. image:: https://anaconda.org/conda-forge/timezonefinder/badges/version.svg   :target: https://anaconda.org/conda-forge/timezonefinder

Multiple distances to the same timezone

When I run closest_timezone_at, I thought that it would return one distance value per timezone. However, when I run it I sometimes get multiple results for one timezone. For example, the following:

tf.closest_timezone_at(lng=-85.2692, lat=31.6575, delta_degree=8,return_distances=True, force_evaluation=True, exact_computation=True)

returns two hits for the New York timezone

('America/New_York', array([ 14.21944659, 754.67091603, 749.29385281, 741.37317121, 704.2011185 , 724.31508828, 699.01969573, 781.7355791 , 551.5451686 , 771.86319838, 14.21944659, 791.60531965]), ['America/Chicago', 'America/Indiana/Indianapolis', 'America/Indiana/Petersburg', 'America/Indiana/Vincennes', 'America/Kentucky/Louisville', 'America/Indiana/Marengo', 'America/Indiana/Tell_City', 'America/Indiana/Vevay', 'America/Kentucky/Monticello', 'America/Nassau', 'America/New_York', 'America/New_York'])

Is this a bug or a feature?

timezonefinder vs timezonefinderL

I am trying to understand the implications of using one vs the other, and have a few questions:

  1. With memory mode = false, wouldn't using timezonefinderL be equivalent to using timezonefinder's timezone_at, in terms of speed and memory load? Since that function supposedly uses only shortcuts, same as timezonefinderL.

  2. Wouldn't it be possible to provide a "limited" memory mode that only loads shortcuts for timezonefinder, to get the best of both world: fast lookups in most cases, and the option to do a deeper lookup when the tz returned is None.

from timezonefinder import TimezoneFinder [type error]

using from timezonefinder import TimezoneFinder. Returns a type error. Not sure if it is OS dependent? I am currently running a Win 8.1, python 2.7 (Anaconda dist)

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-187-ffb6df41970c> in <module>()
----> 1 from timezonefinder import TimezoneFinder

C:\Users\Shetty\Anaconda\lib\site-packages\timezonefinder\__init__.py in <module>()
      1 from __future__ import absolute_import, division, print_function, unicode_literals
      2 
----> 3 from .timezonefinder import TimezoneFinder
      4 
      5 __version__ = '1.5.6'

C:\Users\Shetty\Anaconda\lib\site-packages\timezonefinder\timezonefinder.py in <module>()
     15 
     16 if numba is not None:
---> 17     from .helpers_numba import coord2int, distance_to_polygon_exact, distance_to_polygon, inside_polygon, all_the_same
     18 else:
     19     from .helpers import coord2int, distance_to_polygon_exact, inside_polygon, all_the_same, distance_to_polygon

C:\Users\Shetty\Anaconda\lib\site-packages\timezonefinder\helpers_numba.py in <module>()
      6 
      7 
----> 8 @jit('i1(i4,i4,i4,i4,i4,i4)', nopython=True, cache=True)
      9 def position_to_line(x, y, x1, x2, y1, y2):
     10     """tests if a point pX(x,y) is Left|On|Right of an infinite line from p1 to p2

C:\Users\Shetty\Anaconda\lib\site-packages\numba\decorators.pyc in jit(signature_or_function, locals, target, cache, **options)
    147                    targetoptions=options)
    148     if pyfunc is not None:
--> 149         return wrapper(pyfunc)
    150     else:
    151         return wrapper

C:\Users\Shetty\Anaconda\lib\site-packages\numba\decorators.pyc in wrapper(func)
    161             return _DisableJitWrapper(func)
    162         disp = dispatcher(py_func=func, locals=locals,
--> 163                           targetoptions=targetoptions)
    164         if cache:
    165             disp.enable_caching()

C:\Users\Shetty\Anaconda\lib\site-packages\numba\dispatcher.pyc in __init__(self, py_func, locals, targetoptions)
    274         self.targetctx = self.targetdescr.target_context
    275 
--> 276         pysig = utils.pysignature(py_func)
    277         arg_count = len(pysig.parameters)
    278 

C:\Users\Shetty\Anaconda\lib\site-packages\funcsigs\__init__.pyc in signature(obj)
     57 
     58     if not callable(obj):
---> 59         raise TypeError('{0!r} is not a callable object'.format(obj))
     60 
     61     if isinstance(obj, types.MethodType):

TypeError: u'i1(i4,i4,i4,i4,i4,i4)' is not a callable object

ValueError on import, Python 3.6.7 + timezonefinder 3.4.2 + numba 0.42.1

When trying to import timezonefinder with numba installed (without numba it works fine) following error is raised:

LoweringError: Failed in nopython mode pipeline (step: nopython mode backend)
Cannot lower constant of type 'readonly bytes(uint8, 1d, C)'

File "../../../.local/lib/python3.6/site-packages/timezonefinder/helpers_numba.py", line 312:
def rectify_coordinates(lng, lat):
    <source elided>
    if lng > 180.0 or lng < -180.0 or lat > 90.0 or lat < -90.0:
        raise ValueError(b'The coordinates should be given in degrees. They are out ouf bounds.')
        ^

[1] During: lowering "$const32.2 = const(bytes, b'The coordinates should be given in degrees. They are out ouf bounds.')" at python3.6/site-packages/timezonefinder/helpers_numba.py (312)

This was most probably introduced in 3.4.2 by fix of #70 (does not occur in 3.4.1)

Ocean Locations

Readme says current data set in use: precompiled timezone-boundary-builder (without oceans).

All my points are in ocean, Is there any way I can use data with ocean?

I tried several locations in sea. It returns None.

pointer variable not initialised if force_evaluation is False

From our unit tests:

   troupe.utils.geo_lookup: ERROR: Failed to get timezone for 13,100
   Traceback (most recent call last):
     File "/home/saltmaster/wod.git/troupe/src/utils/geo_lookup.py", line 41, in timezone_at_location
       tz_name = TIMEZONE_FINDER.closest_timezone_at(lat=lat, lng=lon)
     File "/home/saltmaster/conda/envs/troupe/lib/python3.6/site-packages/timezonefinder/functional.py", line 27, in wrapper
       return func(*args, **kwargs)
     File "/home/saltmaster/conda/envs/troupe/lib/python3.6/site-packages/timezonefinder/timezonefinder.py", line 442, in closest_timezone_at
       while pointer < polygons_in_list:
   UnboundLocalError: local variable 'pointer' referenced before assignment

Also, it's just super clear from reading the code.

'uninhabited' returned error

Hi MrMinimal64,

I came across your timezonefinder and realized it would be perfect for my project, so I tried using it. I have been trying to use the timezone_at() method, but I receive an answer of 'uninhabited' for every location I put in.

To test this further, I tried using the geo-coordinates of New York, NY for timezone_at(), certain_timezone_at(), and closest_timezone_at(), and received a response of 'uninhabited' for all three. The response to my TimezoneFinder.using_numba() is False. My version of timezonefinder is 1.5.6

Any clues as to how fix this would be greatly appreciated. Thanks for the hard work on this library; it seems like it would be really great if it worked properly for me!

Use parallel computing

Is this really necessary? Queries are quite fast already with numba and parallelism introduces new challenges and dependencies...

For closest_timezone_at() it could offer a big additional speed boost, because distances from a the polygons are independent and (almost) all need to be computed.

Also with the timezone_at algorithms it may be interesting to check if the point is inside of multiple polygons at once and just stop if one matches.

What about:
http://www.parallelpython.com/

This should work automatically if the dependencies are all installed (like with numba). And there should be a function for checking if parallelism is being used.

Error when querying timezone for some extreme values of latitude, longitude

Hi, this might not be super important but for the sake of correctness:

Some of extreme values of latitude/longitude cannot be handled correctly by timezonefinder. For instance, following examples would result in an error instead of returning 'None'.

python -m timezonefinder.timezonefinder 180.0 0.0
python -m timezonefinder.timezonefinder 179.0 -90.0

Error:

Traceback (most recent call last):
  File "/usr/lib/python3.6/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/usr/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/home/dudnik/Projects/timezonefinder/timezonefinder/timezonefinder.py", line 587, in <module>
    tz = tf.timezone_at(lng=longitude, lat=latitude)
  File "/home/dudnik/Projects/timezonefinder/timezonefinder/functional.py", line 27, in wrapper
    return func(*args, **kwargs)
  File "/home/dudnik/Projects/timezonefinder/timezonefinder/timezonefinder.py", line 487, in timezone_at
    return timezone_names[unpack(b'<H', self.shortcuts_unique_id.read(2))[0]]
struct.error: unpack requires a buffer of 2 bytes

Basically some values of longitude and latitude would cause 'shortcut_id_x' and 'shortcut_id_y' result in a position which is out of bounds of 'shortcuts_unique_id.bin' file.

Keeping/Caching Polygon data

Test if loading polygons (or caching them) into Memory gives a speed advantage.

Mode should then be configurable by the user.

Might be interesting for people who only care about performance.

Conda-Forge Package

I have not seen a package for timezonefinder on conda. More information about it can be found here https://www.continuum.io/downloads. I am in the process of making one on conda-forge and was wondering if @MrMinimal64 would like to be a maintainer of this as well?

Thanks!

Also use shapely

Test results for tzwhere(shapely=True)

TIMES for 10000 realistic queries:
tzwhere: 0:00:00.772074
timezonefinder: 0:00:00.867903
0.89 times faster

TIMES for 10000 random queries:
tzwhere: 0:00:00.563584
timezonefinder: 0:00:00.570806
0.99 times faster

kwargs_only not in conda

Using the package kwargs_only prevents builds on conda-forge as it is not currently a package contained in conda. Are there alternative workaround options (e.g. Do future releases of timezonefinder need to support Python 2 or can they be Python 3 only)?

six dependency missing

As mentioned in the README.rst, library six is now required but, not set up as a required dependency. It is not resolved automatically when installing timezonefinder.

Suggested:

Drop Python2 support

Just as a heads-up:
As many other projects (cf. https://python3statement.org/) I decided to drop the support for python2 with the next timezonefinder release. This is justified by the past compatibility issues and the increased effort of maintaining the compatibility (more tests, dependencies, code...).
The new release hence will be "4.0.0".

test coverage

  • enable and display the test coverage.
  • write tests to improve coverage

write tests for numba_helpers

copy and modify the tests in helpers_test.py to test the precompiled helper functions
(all input has to converted into numpy arrays)

Using recompiled data files

Unless I missed something, the only way to use custom map files currently, is to use the package as a standalone program.

It would be great if it was possible to provide a path to custom files, when using it as a package. I have modified the code to do that here and it seems to work fine (note that you might need to change the way the timezone_names is loaded, since it currently gets set once at the global level).

Let me know if you'd prefer a pull request, and I can probably provide one:

    def __init__(self, bin_file_location, in_memory=False):
        self.in_memory = in_memory

        if self.in_memory:
            self.fromfile = tzf.fromfile_memory
        else:
            self.fromfile = tzf.fromfile

         bin_file_names = ('poly_zone_ids', 'poly_coord_amount', 'poly_adr2data',
        'poly_data', 'poly_max_values', 'poly_nr2zone_id', 'hole_poly_ids',
        'hole_coord_amount', 'hole_adr2data', 'hole_data', 'shortcuts_entry_amount',
        'shortcuts_adr2data', 'shortcuts_data', 'shortcuts_unique_id')
        
        for bf_name in bin_file_names:
            if bin_file_location is None:
                 bf = self.open_binary('timezonefinder', f'{bf_name}.bin')
            else:
                 bf = open(os.path.join(bin_file_location, f'{bf_name}.bin'), mode='rb')
            setattr(self, bf_name, bf)

[...]

        # Overwrite JSON file being loaded in the parent class:
        if bin_file_location is not None:
            with open(os.path.join(bin_file_location, TIMEZONE_NAMES_FILE), 'r') as f:
                timezone_names = json.loads(f.read())

Question: inclusion of simplified data prefered?

I am currently working on a simple GUI for this package and while visualizing the actual timezone polygons used internally in a map, I realized that for the most use cases, I can think of, the data is unnecessarily complex (e.g. small detailed islands on coastlines...)

Unfortunately the GUI is not finished yet, so I cannot really show the exact level of detail, but hopefully my point is understandable. (the JSON of a polygon of one zone is usually more than 100KB big)

So my question is:
Are there any objections to (just?!) including simplified data (=geometries) starting with the next release? Simplification just means certain points would additionally be classified as "inside a zone", without reassigning points which originally belong to a different zone (<- less complex polygons).
In general I am interested in what you use this package for.

Your answers would simply influence where and how I would upload the results. Thanks for your feedback.

extract own timezone boundaries

instead of using the vanilla precompiled boundaries in the timezone-boundary-builder
releases
, which are fairly huge and include territorial waters, it could make sense to use the timezone-boundary-builder
tool itself to extract different boundaries.

desired properties:

  • fewer vertices (less detail in the timezone polygons -> smaller data, faster algorithms)

  • exclude territorial waters ( polygons follow the shorelines -> looking for closest timezone with closest_timezone_at() possible again)

I have not looked into it yet, so i cannot predict how easy it is to accomplish this.
I also do not know how relevant this is to you users.

IOError: first argument must be an open file

Hi everyone, I'm using this library to get timezone from user addresses, I'm getting this error for the following coordinates:

tf.timezone_at(lng=-87.6330737, lat=41.9112897)

Can you help me please telling what it means in this case?, this seems a numpy issue, but not sure what's wrong in this case.

Thanks in advance.

test_convert2coords triggers NotImplementedError in Numba

Hello,

Depending on Numba version, this test fails. Works with Numba 0.42 but crashes with 0.34:

self = <numba.runtime.context.NRTContext object at 0x7f00c42f2cc0>
builder = <llvmlite.llvmpy.core.Builder object at 0x7f00c42f9f28>
root_type = list(list(float64))
typ = memory-managed *payload(list(list(float64)))
value = <ir.ExtractValue 'extracted.meminfo.61' of type 'i8*', opname 'extractvalue', operands [<ir.LoadInstr '.979' of type '{i8*, i8*}', opname 'load', operands [<ir.AllocaInstr '$0.17' of type '{i8*, i8*}*', opname 'alloca', operands ()>]>]>
funcname = 'NRT_decref'
getters = (functools.partial(<function StructModel.traverse.<locals>.getter at 0x7f00c42fdea0>, 'meminfo'),)

    def _call_incref_decref(self, builder, root_type, typ, value,
                                funcname, getters=()):
        self._require_nrt()
    
        from numba.runtime.nrtdynmod import incref_decref_ty
    
        data_model = self._context.data_model_manager[typ]
    
        members = data_model.traverse(builder)
        for mtyp, getter in members:
            self._call_incref_decref(builder, root_type, mtyp, value,
                                     funcname, getters + (getter,))
    
        if data_model.has_nrt_meminfo():
            # Call the chain of getters to compute the member value
            for getter in getters:
                value = getter(value)
            try:
                meminfo = data_model.get_nrt_meminfo(builder, value)
            except NotImplementedError as e:
>               raise NotImplementedError("%s: %s" % (root_type, str(e)))
E               numba.errors.LoweringError: Failed at nopython (nopython mode backend)
E               list(list(float64)): unsupported nested memory-managed object
E               File "timezonefinder/helpers_numba.py", line 330
E               [1] During: lowering "$0.17 = build_list(items=[Var($0.8, /home/acecile/packaging/python-timezonefinder/timezonefinder-4.0.2/.pybuild/pythonX.Y_3.5/build/timezonefinder/helpers_numba.py (330)), Var($0.16, /home/acecile/packaging/python-timezonefinder/timezonefinder-4.0.2/.pybuild/pythonX.Y_3.5/build/timezonefinder/helpers_numba.py (330))])" at /home/acecile/packaging/python-timezonefinder/timezonefinder-4.0.2/.pybuild/pythonX.Y_3.5/build/timezonefinder/helpers_numba.py (330)

/usr/lib/python3/dist-packages/numba/runtime/context.py:188: LoweringError

You should probably detects this and disable Numba for this part of code if the version is too old.

Best regards, Adam.

Pin setup.py install_requires versions

First, thanks for timezonefinder!

I'm using the PyPI v3.2.0 of timezonefinder which has a setup requirement of numpy. The pinned requirements.txt for version v3.2.0 is numpy==1.15.3. On 2019/01/13 v1.16.0 of numpy was released. Since the version was not pinned in setup.py to 1.15.3, my project was automatically updated to numpy 1.16.0, which broke the application.

Please consider pinning install_requires package versions so timezonefinder doesn't inadvertently automatically upgrade dependencies to the latest version.

ValueError, coords out of bounds on initial import w/ 3.4.1 and python 2.7

If timezonefinder does not support Python 2.7, that's perfectly fine and this issue should be refiled against the conda-forge feedstock so that it only builds python 3.x packages.

pparente@vm4-002 ~ ❯❯❯ conda create -n tzfinder 'python=2.7*' 'timezonefinder>=3.4.1'
Solving environment: done

## Package Plan ##

  environment location: /home/pparente/miniconda/envs/tzfinder

  added / updated specs:
    - python=2.7
    - timezonefinder[version='>=3.4.1']


The following packages will be downloaded:

    package                    |            build
    ---------------------------|-----------------
    numpy-1.16.0               |py27_blas_openblashb06ca3d_0         9.1 MB  conda-forge
    openblas-0.3.3             |       ha44fe06_1        13.7 MB  conda-forge
    blas-1.1                   |         openblas           1 KB  conda-forge
    libgfortran-3.0.0          |                1         281 KB  conda-forge
    ------------------------------------------------------------
                                           Total:        23.0 MB

The following NEW packages will be INSTALLED:

    blas:                1.1-openblas                        conda-forge
    ca-certificates:     2018.11.29-ha4d7672_0               conda-forge
    certifi:             2018.11.29-py27_1000                conda-forge
    enum34:              1.1.6-py27_1001                     conda-forge
    funcsigs:            1.0.2-py_3                          conda-forge
    importlib_resources: 1.0.2-py27_1000                     conda-forge
    libffi:              3.2.1-hfc679d8_5                    conda-forge
    libgcc-ng:           7.2.0-hdf63c60_3                    conda-forge
    libgfortran:         3.0.0-1                             conda-forge
    libstdcxx-ng:        7.2.0-hdf63c60_3                    conda-forge
    llvmlite:            0.26.0-py27hd28b015_0               conda-forge
    ncurses:             6.1-hfc679d8_2                      conda-forge
    numba:               0.41.0-py27hf8a1672_0               conda-forge
    numpy:               1.16.0-py27_blas_openblashb06ca3d_0 conda-forge [blas_openblas]
    openblas:            0.3.3-ha44fe06_1                    conda-forge
    openssl:             1.0.2p-h470a237_2                   conda-forge
    pathlib2:            2.3.3-py27_1000                     conda-forge
    pip:                 18.1-py27_1000                      conda-forge
    python:              2.7.15-h33da82c_6                   conda-forge
    readline:            7.0-haf1bffa_1                      conda-forge
    scandir:             1.9.0-py27h470a237_0                conda-forge
    setuptools:          40.6.3-py27_0                       conda-forge
    singledispatch:      3.4.0.3-py27_1000                   conda-forge
    six:                 1.12.0-py27_1000                    conda-forge
    sqlite:              3.26.0-hb1c47c0_0                   conda-forge
    timezonefinder:      3.4.1-py_0                          conda-forge
    tk:                  8.6.9-ha92aebf_0                    conda-forge
    typing:              3.6.6-py27_1000                     conda-forge
    wheel:               0.32.3-py27_0                       conda-forge
    zlib:                1.2.11-h470a237_4                   conda-forge

Proceed ([y]/n)? y


Downloading and Extracting Packages
numpy-1.16.0         | 9.1 MB    | ################################################################################### | 100%
openblas-0.3.3       | 13.7 MB   | ################################################################################### | 100%
blas-1.1             | 1 KB      | ################################################################################### | 100%
libgfortran-3.0.0    | 281 KB    | ################################################################################### | 100%
Preparing transaction: done
Verifying transaction: done
Executing transaction: done
#
# To activate this environment, use
#
#     $ conda activate tzfinder
#
# To deactivate an active environment, use
#
#     $ conda deactivate

pparente@vm4-002 ~ ❯❯❯ conda activate tzfinder
(tzfinder) pparente@vm4-002 ~ ❯❯❯ python
Python 2.7.15 | packaged by conda-forge | (default, Nov 29 2018, 06:43:57)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-15)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import timezonefinder
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/pparente/miniconda/envs/tzfinder/lib/python2.7/site-packages/timezonefinder/__init__.py", line 3, in <module>
    from .timezonefinder import TimezoneFinder
  File "/home/pparente/miniconda/envs/tzfinder/lib/python2.7/site-packages/timezonefinder/timezonefinder.py", line 22, in <module>
    from .helpers_numba import coord2int, distance_to_polygon_exact, distance_to_polygon, inside_polygon, \
  File "/home/pparente/miniconda/envs/tzfinder/lib/python2.7/site-packages/timezonefinder/helpers_numba.py", line 309, in <module>
    @njit(dtype_2float_tuple(f8, f8), cache=True)
  File "/home/pparente/miniconda/envs/tzfinder/lib/python2.7/site-packages/numba/decorators.py", line 198, in wrapper
    disp.compile(sig)
  File "/home/pparente/miniconda/envs/tzfinder/lib/python2.7/site-packages/numba/compiler_lock.py", line 32, in _acquire_compile_lock
    return func(*args, **kwargs)
  File "/home/pparente/miniconda/envs/tzfinder/lib/python2.7/site-packages/numba/dispatcher.py", line 655, in compile
    cres = self._compiler.compile(args, return_type)
  File "/home/pparente/miniconda/envs/tzfinder/lib/python2.7/site-packages/numba/dispatcher.py", line 82, in compile
    pipeline_class=self.pipeline_class)
  File "/home/pparente/miniconda/envs/tzfinder/lib/python2.7/site-packages/numba/compiler.py", line 926, in compile_extra
    return pipeline.compile_extra(func)
  File "/home/pparente/miniconda/envs/tzfinder/lib/python2.7/site-packages/numba/compiler.py", line 374, in compile_extra
    return self._compile_bytecode()
  File "/home/pparente/miniconda/envs/tzfinder/lib/python2.7/site-packages/numba/compiler.py", line 857, in _compile_bytecode
    return self._compile_core()
  File "/home/pparente/miniconda/envs/tzfinder/lib/python2.7/site-packages/numba/compiler.py", line 844, in _compile_core
    res = pm.run(self.status)
  File "/home/pparente/miniconda/envs/tzfinder/lib/python2.7/site-packages/numba/compiler_lock.py", line 32, in _acquire_compile_lock
    return func(*args, **kwargs)
  File "/home/pparente/miniconda/envs/tzfinder/lib/python2.7/site-packages/numba/compiler.py", line 255, in run
    raise patched_exception
numba.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend)
cannot determine Numba type of <type 'unicode'>

File "miniconda/envs/tzfinder/lib/python2.7/site-packages/timezonefinder/helpers_numba.py", line 312:
def rectify_coordinates(lng, lat):
    <source elided>
    if lng > 180.0 or lng < -180.0 or lat > 90.0 or lat < -90.0:
        raise ValueError('The coordinates should be given in degrees. They are out ouf bounds.')
        ^

Too many open files: '/usr/local/lib/python3.6/site-packages/timezonefinder/poly_zone_ids.bin'

I am using this library within my python app hosted in a docker image, and when I started using it it was okay, and now I'm having this issue. My guess is that somewhere in the code the object is not being garbage collected/destroyed and the binaries remain open over time causing the issue. Any inputs?

Unable to find source-code formatter for language: text. Available languages are: actionscript, ada, applescript, bash, c, c#, c++, cpp, css, erlang, go, groovy, haskell, html, java, javascript, js, json, lua, none, nyan, objc, perl, php, python, r, rainbow, ruby, scala, sh, sql, swift, visualbasic, xml, yaml
OSError: [Errno 24] Too many open files: '/usr/local/lib/python3.6/site-packages/timezonefinder/poly_zone_ids.bin'
172.17.0.21 - - [08/May/2018 07:10:23] "POST /1.0/predict HTTP/1.1" 500 -
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1997, in call

File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1985, in wsgi_app

File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1540, in handle_exception

File "/usr/local/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise

File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1982, in wsgi_app

File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1614, in full_dispatch_request

File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1517, in handle_user_exception

File "/usr/local/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise

File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1612, in full_dispatch_request

File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1598, in dispatch_request

File "/usr/src/app/app.py", line 141, in is_at_venue

File "/usr/src/app/utils/AtVenueModel.py", line 38, in init

File "/usr/src/app/utils/TemporalTools.py", line 12, in getLocalTime

File "/usr/local/lib/python3.6/site-packages/timezonefinder/timezonefinder.py", line 104, in init

adding Tests for Numba

modify the tox setting for also running the tests with Numba enabled.
Things might go wrong there.

Suggestion: vectorizing

Your package is very helpful, thanks a lot 😄

Just thinking, maybe you can vectorize all the functions so they can be use on a numpy array or pandas DataFrame, it'll be awesome for those who work with geo data

I know we can use .apply but why not vectorize 😉 ?

Support for pandas dataframe

Hi.

One feature that I am missing is the possibility to compute the timezones from a pandas dataframe containing Latitude and Longitude.
If you think this might be a feature that suites into this package, I can try to implement it.

.bin file generation script

I can't see how the .bin file is created, is there a script you have that isn't checked in to Github? It would be nice to make it reproducible/updatable in the future.

Writing tz_world data conversion tool

Writing script to convert original timezone data from
http://efele.net/maps/tz/world/
directly into the needed binary file.
This is important to keep the data up to date (countries may change their timezones?!).
Also make the timezone_names being loaded from a separate file (names and numeration are changing)

See this post: http://gis.stackexchange.com/questions/7339/converting-shapefiles-to-text-ascii-files

import shapefile
sf = shapefile.Reader("shapefiles/blockgroups")
shapes = sf.shapes()

Shapes will contain an array of shapes

points = shapes[0].points

http://www.gdal.org/drv_csv.html

For now only the conversion of the tzwhere data (as .csv) is supported with the file_converter.py

Readme not rendering on PyPI

The problem is in the REAME.rst under Installation, there is a broken link (missing space between "feedstock" and the <). This is causing readme_renderer to choke, which then causes long_description to fail to render on PyPI.

You can check the README yourself with:

pip install readme_renderer
python setup.py check -r -s

Loading Error

Hi MrMinimal64,

Thank you for your library, it seems perfect for my project ! Indeed I have to convert many local times to UTC times from latitude and longitude features.

That's why I installed your project.
However I can't load your code. When I write:

from timezonefinder import TimezoneFinder

I have the following output:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-8-ffb6df41970c> in <module>()
----> 1 from timezonefinder import TimezoneFinder

/home/ecoast/anaconda2/lib/python2.7/site-packages/timezonefinder/__init__.py in <module>()
      1 from __future__ import absolute_import, division, print_function, unicode_literals
      2 
----> 3 from .timezonefinder import TimezoneFinder
      4 
      5 __version__ = '1.5.4'

/home/ecoast/anaconda2/lib/python2.7/site-packages/timezonefinder/timezonefinder.py in <module>()
     15 
     16 if numba is not None:
---> 17     from .helpers_numba import coord2int, distance_to_polygon, inside_polygon
     18 else:
     19     from .helpers import coord2int, distance_to_polygon, inside_polygon

/home/ecoast/anaconda2/lib/python2.7/site-packages/timezonefinder/helpers_numba.py in <module>()
      6 
      7 
----> 8 @jit('uint(i4,i4,i4,i4,i4,i4)', nopython=True, cache=True)
      9 def position_to_line(x, y, x1, x2, y1, y2):
     10     """tests if a point pX(x,y) is Left|On|Right of an infinite line from p1 to p2
could
/home/ecoast/anaconda2/lib/python2.7/site-packages/numba/decorators.py in jit(signature_or_function, locals, target, cache, **options)
    146 
    147     wrapper = _jit(sigs, locals=locals, target=target, cache=cache,
--> 148                    targetoptions=options)
    149     if pyfunc is not None:
    150         return wrapper(pyfunc)

/home/ecoast/anaconda2/lib/python2.7/site-packages/numba/decorators.py in wrapper(func)
    162         if config.DISABLE_JIT and not target == 'npyufunc':
    163             return _DisableJitWrapper(func)
--> 164         disp = dispatcher(py_func=func, locals=locals,
    165                           targetoptions=targetoptions,
    166                           **dispatcher_args)

/home/ecoast/anaconda2/lib/python2.7/site-packages/numba/dispatcher.py in __init__(self, py_func, locals, targetoptions, impl_kind)
    380         locals: dict, optional
    381             Mapping of local variable names to Numba types.  Used to override
--> 382             the types deduced by the type inference engine.
    383         targetoptions: dict, optional
    384             Target-specific config options.

/home/ecoast/anaconda2/lib/python2.7/site-packages/funcsigs/__init__.pyc in signature(obj)
     57 
     58     if not callable(obj):
---> 59         raise TypeError('{0!r} is not a callable object'.format(obj))
     60 
     61     if isinstance(obj, types.MethodType):

TypeError: u'uint(i4,i4,i4,i4,i4,i4)' is not a callable object

And yet I checked all requirements and if my libraries were updated.
If you can help me I will be very grateful to you !

Get the Time Zone offset

Is there a way to get the Time Zone GMT offset (-1, +14, 0, ...), instead of the Time Zone name?

timezonefinder can't be used as an embedded module

If instead of using the Python interpreter, timezonefinder is used embedded in CPython, an ImportError exception will occur, rendering it unusable:

File ".../lib/python2.7/site-packages/timezonefinder/__init__.py", line 3, in <module> from .timezonefinder import TimezoneFinder File ".../lib/python2.7/site-packages/timezonefinder/timezonefinder.py", line 7, in <module> from sys import argv, exit ImportError: cannot import name argv

This occurs because sys.path is not available to the embedded interpreter.

A simple fix to this would be to make the import a local one inside the block:

if __name__ == '__main__':

Support Python 2.7

I'm using timezonefinder with Python 2.7 because it said Python 2 compatible in an older version :)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.