0
# Global Convenience Functions
1
2
Module-level functions that provide simple access to timezone lookup functionality using a singleton TimezoneFinder instance. These functions offer maximum convenience for simple use cases but are not thread-safe.
3
4
## Capabilities
5
6
### Core Lookup Functions
7
8
Primary timezone lookup functions that handle the most common use cases. All functions use a shared global TimezoneFinder instance that is created lazily on first use.
9
10
```python { .api }
11
def timezone_at(*, lng: float, lat: float) -> Optional[str]:
12
"""
13
Find timezone at given coordinates using global TimezoneFinder instance.
14
15
Note: This function is not thread-safe. For multi-threaded environments,
16
create separate TimezoneFinder instances.
17
18
Parameters:
19
- lng: Longitude in degrees (-180.0 to 180.0)
20
- lat: Latitude in degrees (-90.0 to 90.0)
21
22
Returns:
23
- Timezone name of matching polygon or None
24
"""
25
26
def timezone_at_land(*, lng: float, lat: float) -> Optional[str]:
27
"""
28
Find land timezone only, excluding ocean timezones.
29
30
Note: This function is not thread-safe. For multi-threaded environments,
31
create separate TimezoneFinder instances.
32
33
Parameters:
34
- lng: Longitude in degrees (-180.0 to 180.0)
35
- lat: Latitude in degrees (-90.0 to 90.0)
36
37
Returns:
38
- Land timezone name or None when ocean timezone would be matched
39
"""
40
41
def unique_timezone_at(*, lng: float, lat: float) -> Optional[str]:
42
"""
43
Find timezone if unique within the corresponding shortcut area.
44
45
Note: This function is not thread-safe. For multi-threaded environments,
46
create separate TimezoneFinder instances.
47
48
Parameters:
49
- lng: Longitude in degrees (-180.0 to 180.0)
50
- lat: Latitude in degrees (-90.0 to 90.0)
51
52
Returns:
53
- Timezone name if unique in shortcut area, None if multiple or no zones
54
"""
55
56
def certain_timezone_at(*, lng: float, lat: float) -> Optional[str]:
57
"""
58
Find timezone with exhaustive polygon checking.
59
60
Note: This function is not thread-safe. For multi-threaded environments,
61
create separate TimezoneFinder instances.
62
63
Note: Only meaningful with custom timezone data having incomplete coverage.
64
Less performant than timezone_at().
65
66
Parameters:
67
- lng: Longitude in degrees (-180.0 to 180.0)
68
- lat: Latitude in degrees (-90.0 to 90.0)
69
70
Returns:
71
- Timezone name if point is certainly within a polygon, None otherwise
72
"""
73
```
74
75
### Geometry Access Function
76
77
Advanced function for retrieving detailed timezone polygon geometry data.
78
79
```python { .api }
80
def get_geometry(
81
tz_name: Optional[str] = "",
82
tz_id: Optional[int] = 0,
83
use_id: bool = False,
84
coords_as_pairs: bool = False
85
) -> List[Union[List[CoordPairs], List[CoordLists]]]:
86
"""
87
Retrieve geometry of a timezone polygon using global TimezoneFinder instance.
88
89
Note: This function is not thread-safe. For multi-threaded environments,
90
create separate TimezoneFinder instances.
91
92
Parameters:
93
- tz_name: Timezone name (e.g., 'Europe/Berlin')
94
- tz_id: Timezone ID (index in timezone_names list)
95
- use_id: If True, use tz_id instead of tz_name
96
- coords_as_pairs: If True, return coordinates as [(lng,lat), ...] pairs,
97
if False, return as ([longitudes], [latitudes]) lists
98
99
Returns:
100
- Multipolygon data structure: [[polygon1, hole1, hole2...], [polygon2, ...], ...]
101
Each polygon/hole formatted as coordinate pairs or separate lists based on coords_as_pairs
102
"""
103
```
104
105
## Usage Examples
106
107
### Simple Timezone Lookup
108
109
```python
110
from timezonefinder import timezone_at, timezone_at_land
111
112
# Basic timezone lookup
113
tz = timezone_at(lng=13.358, lat=52.5061)
114
print(tz) # 'Europe/Berlin'
115
116
# Land timezone only (excludes ocean timezones)
117
land_tz = timezone_at_land(lng=0.0, lat=0.0)
118
print(land_tz) # None (ocean location)
119
120
ocean_tz = timezone_at(lng=0.0, lat=0.0)
121
print(ocean_tz) # 'Etc/GMT' (ocean timezone)
122
```
123
124
### Specialized Lookup Functions
125
126
```python
127
from timezonefinder import unique_timezone_at, certain_timezone_at
128
129
# Unique timezone in shortcut area
130
unique_tz = unique_timezone_at(lng=13.358, lat=52.5061)
131
print(unique_tz) # 'Europe/Berlin' if unique in area, None if multiple zones
132
133
# Exhaustive polygon checking
134
certain_tz = certain_timezone_at(lng=13.358, lat=52.5061)
135
print(certain_tz) # 'Europe/Berlin' if certainly within polygon
136
```
137
138
### Geometry Retrieval
139
140
```python
141
from timezonefinder import get_geometry
142
143
# Get geometry by timezone name
144
geometry = get_geometry(tz_name='Europe/Berlin', coords_as_pairs=False)
145
print(f"Number of polygons: {len(geometry)}")
146
147
# Each polygon contains boundary + holes
148
for i, polygon_with_holes in enumerate(geometry):
149
boundary = polygon_with_holes[0] # First is the boundary
150
holes = polygon_with_holes[1:] # Rest are holes
151
152
lngs, lats = boundary
153
print(f"Polygon {i}: {len(lngs)} boundary points, {len(holes)} holes")
154
155
# Get geometry as coordinate pairs
156
geometry_pairs = get_geometry(tz_name='Europe/Berlin', coords_as_pairs=True)
157
for i, polygon_with_holes in enumerate(geometry_pairs):
158
boundary = polygon_with_holes[0] # [(lng1, lat1), (lng2, lat2), ...]
159
print(f"Polygon {i}: First point {boundary[0]}")
160
```
161
162
### Batch Processing (Non-Thread-Safe)
163
164
```python
165
from timezonefinder import timezone_at
166
167
# Process multiple coordinates
168
coordinates = [
169
(13.358, 52.5061), # Berlin
170
(-74.0060, 40.7128), # New York
171
(139.6917, 35.6895), # Tokyo
172
(2.3522, 48.8566), # Paris
173
(-0.1276, 51.5074) # London
174
]
175
176
results = []
177
for lng, lat in coordinates:
178
tz = timezone_at(lng=lng, lat=lat)
179
results.append((lng, lat, tz))
180
print(f"({lat:.3f}, {lng:.3f}) -> {tz}")
181
```
182
183
### Error Handling
184
185
```python
186
from timezonefinder import timezone_at, get_geometry
187
188
# Invalid coordinates
189
try:
190
tz = timezone_at(lng=200.0, lat=52.5061) # Invalid longitude
191
except ValueError as e:
192
print(f"Coordinate error: {e}")
193
194
# Invalid timezone name
195
try:
196
geometry = get_geometry(tz_name='Invalid/Timezone')
197
except ValueError as e:
198
print(f"Timezone error: {e}")
199
200
# Using timezone ID instead of name
201
try:
202
geometry = get_geometry(tz_id=0, use_id=True)
203
print("Successfully retrieved geometry by ID")
204
except ValueError as e:
205
print(f"ID error: {e}")
206
```
207
208
## Thread Safety Considerations
209
210
Global functions are **not thread-safe** because they share a singleton TimezoneFinder instance. For concurrent access:
211
212
```python
213
# ❌ NOT thread-safe
214
import threading
215
from timezonefinder import timezone_at
216
217
def worker(coordinates):
218
for lng, lat in coordinates:
219
tz = timezone_at(lng=lng, lat=lat) # Shared global instance
220
print(tz)
221
222
# This can cause issues with concurrent access
223
224
# ✅ Thread-safe alternative
225
import threading
226
from timezonefinder import TimezoneFinder
227
228
def safe_worker(coordinates):
229
tf = TimezoneFinder() # Each thread gets its own instance
230
for lng, lat in coordinates:
231
tz = tf.timezone_at(lng=lng, lat=lat)
232
print(tz)
233
```
234
235
## Performance Notes
236
237
- Global functions use lazy initialization - the TimezoneFinder instance is created on first use
238
- All subsequent calls reuse the same instance, providing good performance for sequential usage
239
- The global instance uses default settings (not in_memory mode)
240
- For high-performance applications with many lookups, consider using TimezoneFinder instances directly with `in_memory=True`