Skip to content

Time Zones

Timezone

Timezone(maps: Map)

Google time zone client.

Purpose

Retrieves timezone identifiers, UTC offsets, and time-enriched location records.

Attributes:

Name Type Description
timestamp Optional[int]

Unix timestamp used for timezone lookup.

maps Optional[Map]

Google Maps gateway used for timezone requests.

latitude Optional[float]

Current latitude in decimal degrees.

longitude Optional[float]

Current longitude in decimal degrees.

data Optional[Dict]

Most recent timezone API payload.

offset Optional[float]

Computed UTC offset including daylight saving time.

local Optional[str]

Last computed local datetime representation.

rows Optional[list]

Input rows for batch enrichment.

lat_field Optional[str]

Latitude field name for batch enrichment.

lng_field Optional[str]

Longitude field name for batch enrichment.

utc_datetime Optional[datetime]

UTC datetime used for local time conversion.

Initialize timezone lookup state for the supplied Maps gateway.

Purpose

Initialize timezone lookup state for the supplied Maps gateway.

Parameters:

Name Type Description Default
maps Map

Initialized Google Maps API gateway.

required

Returns:

Name Type Description
None None

Initializes instance state.

Source code in mapping.py
def __init__( self, maps: Map ) -> None:
	"""Initialize timezone lookup state for the supplied Maps gateway.

	Purpose:
		Initialize timezone lookup state for the supplied Maps gateway.

	Args:
		maps (Map): Initialized Google Maps API gateway.

	Returns:
		None: Initializes instance state.
	"""
	self.maps = maps
	self.timestamp = None
	self.latitude = None
	self.longitude = None
	self.data = None
	self.offset = None
	self.local = None
	self.rows = None
	self.lat_field = None
	self.lng_field = None
	self.utc_datetime = None

Methods:

validate_coordinates

validate_coordinates(lat: float, lng: float) -> tuple
Purpose

Validate and normalize a latitude and longitude pair.

Parameters:

Name Type Description Default
lat float

Latitude in decimal degrees.

required
lng float

Longitude in decimal degrees.

required

Returns:

Name Type Description
tuple tuple

Validated latitude and longitude.

Source code in mapping.py
def validate_coordinates( self, lat: float, lng: float ) -> tuple:
	"""

		Purpose:
			Validate and normalize a latitude and longitude pair.

		Args:
			lat (float):
				Latitude in decimal degrees.

			lng (float):
				Longitude in decimal degrees.

		Returns:
			tuple:
				Validated latitude and longitude.

	"""
	try:
		throw_if( 'lat', lat )
		throw_if( 'lng', lng )
		if (type( lat ) not in (int, float) or type( lng ) not in (int,
			float) or not math.isfinite( lat ) or not math.isfinite( lng )):
			raise ValueError( 'Coordinates must be finite numeric values.' )
		latitude = lat
		longitude = lng
		if latitude < -90.0 or latitude > 90.0:
			raise ValueError( 'Latitude must be between -90 and 90.' )
		if longitude < -180.0 or longitude > 180.0:
			raise ValueError( 'Longitude must be between -180 and 180.' )
		self.latitude = latitude
		self.longitude = longitude
		return self.latitude, self.longitude

	except Exception as e:
		exception = Error( e )
		exception.module = 'mapping'
		exception.cause = 'Timezone'
		exception.method = "validate_coordinates( self, lat: float, lng: float ) -> tuple"
		raise exception

lookup

lookup(lat: float, lng: float) -> Dict | None
Purpose

Fetch the full Google Time Zone API response for a coordinate.

Parameters:

Name Type Description Default
lat float

Latitude.

required
lng float

Longitude.

required

Returns:

Type Description
Dict | None

Dict | None: Full time zone response payload, including timeZoneId, timeZoneName, rawOffset, dstOffset, and status when available.

Source code in mapping.py
def lookup( self, lat: float, lng: float ) -> Dict | None:
	"""

		Purpose:
			Fetch the full Google Time Zone API response for a coordinate.

		Args:
			lat (float):
				Latitude.

			lng (float):
				Longitude.

		Returns:
			Dict | None:
				Full time zone response payload, including timeZoneId, timeZoneName,
				rawOffset, dstOffset, and status when available.

	"""
	try:
		throw_if( 'lat', lat )
		throw_if( 'lng', lng )
		latitude, longitude = self.validate_coordinates( lat, lng )
		timestamp_value = int( time.time( ) )
		self.latitude = latitude
		self.longitude = longitude
		self.timestamp = timestamp_value
		self.data = self.maps.request( 'timezone/json', {
			'location': f'{self.latitude},{self.longitude}',
			'timestamp': str( self.timestamp ) } )
		return self.data

	except Exception as e:
		exception = Error( e )
		exception.module = 'mapping'
		exception.cause = 'Timezone'
		exception.method = "lookup( self, lat: float, lng: float ) -> Dict | None"
		raise exception

get_id

get_id(lat: float, lng: float) -> Optional[str]
Purpose

Fetch the IANA time zone id for a coordinate.

Parameters:

Name Type Description Default
lat float

Latitude.

required
lng float

Longitude.

required

Returns:

Type Description
Optional[str]

Optional[str]: Time zone id string or None if unavailable.

Source code in mapping.py
def get_id( self, lat: float, lng: float ) -> Optional[ str ]:
	"""

		Purpose:
			Fetch the IANA time zone id for a coordinate.

		Args:
			lat (float):
				Latitude.

			lng (float):
				Longitude.

		Returns:
			Optional[str]:
				Time zone id string or None if unavailable.

	"""
	try:
		throw_if( 'lat', lat )
		throw_if( 'lng', lng )
		self.data = self.lookup( lat, lng )
		if not isinstance( self.data, dict ):
			return None
		return self.data.get( 'timeZoneId' )

	except Exception as e:
		exception = Error( e )
		exception.module = 'mapping'
		exception.cause = 'Timezone'
		exception.method = "get_id( self, lat: float, lng: float ) -> Optional[ str ]"
		raise exception

offset_hours

offset_hours(lat: float, lng: float) -> Optional[float]
Purpose

Fetch the total UTC offset in hours for a coordinate.

Parameters:

Name Type Description Default
lat float

Latitude.

required
lng float

Longitude.

required

Returns:

Type Description
Optional[float]

Optional[float]: Total UTC offset in hours, including daylight-saving offset when returned by the API.

Source code in mapping.py
def offset_hours( self, lat: float, lng: float ) -> Optional[ float ]:
	"""

		Purpose:
			Fetch the total UTC offset in hours for a coordinate.

		Args:
			lat (float):
				Latitude.

			lng (float):
				Longitude.

		Returns:
			Optional[float]:
				Total UTC offset in hours, including daylight-saving offset
				when returned by the API.

	"""
	try:
		throw_if( 'lat', lat )
		throw_if( 'lng', lng )
		self.data = self.lookup( lat, lng )
		if not isinstance( self.data, dict ):
			return None
		raw_offset = self.data.get( 'rawOffset', 0 ) or 0
		dst_offset = self.data.get( 'dstOffset', 0 ) or 0
		offset_value = round( (float( raw_offset ) + float( dst_offset )) / 3600.0, 3 )
		self.offset = offset_value
		return self.offset

	except Exception as e:
		exception = Error( e )
		exception.module = 'mapping'
		exception.cause = 'Timezone'
		exception.method = "offset_hours( self, lat: float, lng: float ) -> Optional[ float ]"
		raise exception

local_time

local_time(
    lat: float,
    lng: float,
    utc_datetime: Optional[datetime] = None,
) -> Dict | None
Purpose

Convert a UTC datetime into local time at a coordinate using the Google Time Zone API rawOffset and dstOffset fields.

Parameters:

Name Type Description Default
lat float

Latitude.

required
lng float

Longitude.

required
utc_datetime Optional[datetime]

Optional UTC datetime. If None, the current UTC time is used.

None

Returns:

Type Description
Dict | None

Dict | None: Dictionary containing timezone metadata, UTC time, local time, and total offset hours.

Source code in mapping.py
def local_time( self, lat: float, lng: float,
	utc_datetime: Optional[ dt.datetime ] = None ) -> Dict | None:
	"""

		Purpose:
			Convert a UTC datetime into local time at a coordinate using the
			Google Time Zone API rawOffset and dstOffset fields.

		Args:
			lat (float):
				Latitude.

			lng (float):
				Longitude.

			utc_datetime (Optional[dt.datetime]):
				Optional UTC datetime. If None, the current UTC time is used.

		Returns:
			Dict | None:
				Dictionary containing timezone metadata, UTC time, local time,
				and total offset hours.

	"""
	try:
		throw_if( 'lat', lat )
		throw_if( 'lng', lng )
		self.data = self.lookup( lat, lng )
		if not isinstance( self.data, dict ):
			return None
		if utc_datetime is None:
			utc_value = dt.datetime.now( dt.timezone.utc )
		else:
			utc_value = utc_datetime
			if utc_value.tzinfo is None:
				utc_value = utc_value.replace( tzinfo=dt.timezone.utc )
			else:
				utc_value = utc_value.astimezone( dt.timezone.utc )
		raw_offset = self.data.get( 'rawOffset', 0 ) or 0
		dst_offset = self.data.get( 'dstOffset', 0 ) or 0
		total_seconds = float( raw_offset ) + float( dst_offset )
		local_value = utc_value + dt.timedelta( seconds=total_seconds )
		offset_value = round( total_seconds / 3600.0, 3 )
		self.utc_datetime = utc_value
		self.offset = offset_value
		self.local = local_value.isoformat( )
		return { 'timeZoneId': self.data.get( 'timeZoneId' ),
			'timeZoneName': self.data.get( 'timeZoneName' ),
			'status': self.data.get( 'status' ), 'rawOffset': raw_offset,
			'dstOffset': dst_offset, 'offset_hours': self.offset,
			'utc_time': self.utc_datetime.isoformat( ), 'local_time': self.local,
			'lat': self.latitude, 'lng': self.longitude }

	except Exception as e:
		exception = Error( e )
		exception.module = 'mapping'
		exception.cause = 'Timezone'
		exception.method = ('local_time( self, **args)')
		raise exception

batch_lookup

batch_lookup(
    rows: list,
    lat_field: str = "lat",
    lng_field: str = "lng",
) -> list
Purpose

Enrich a list of row dictionaries with Google Time Zone API fields.

Parameters:

Name Type Description Default
rows list

List of dictionaries containing latitude and longitude fields.

required
lat_field str

Latitude field name.

'lat'
lng_field str

Longitude field name.

'lng'

Returns:

Name Type Description
list list

List of copied row dictionaries with timezone fields appended.

Source code in mapping.py
def batch_lookup( self, rows: list, lat_field: str = 'lat', lng_field: str = 'lng' ) -> list:
	"""

		Purpose:
			Enrich a list of row dictionaries with Google Time Zone API fields.

		Args:
			rows (list):
				List of dictionaries containing latitude and longitude fields.

			lat_field (str):
				Latitude field name.

			lng_field (str):
				Longitude field name.

		Returns:
			list:
				List of copied row dictionaries with timezone fields appended.

	"""
	try:
		throw_if( 'rows', rows )
		if not isinstance( rows, list ):
			raise ValueError( 'rows must be a list of dictionaries.' )
		lat_field_value = lat_field or 'lat'
		lng_field_value = lng_field or 'lng'
		self.rows = rows
		self.lat_field = lat_field_value
		self.lng_field = lng_field_value
		output = [ ]
		for row in self.rows:
			item = dict( row or { } )
			try:
				lat_value = item.get( self.lat_field )
				lng_value = item.get( self.lng_field )
				data = self.lookup( lat_value, lng_value )
				if not isinstance( data, dict ):
					item[ 'timeZoneId' ] = None
					item[ 'timeZoneName' ] = None
					item[ 'rawOffset' ] = None
					item[ 'dstOffset' ] = None
					item[ 'offset_hours' ] = None
					item[ 'timezone_status' ] = 'not_found'
					item[ 'timezone_error' ] = 'No timezone response returned.'

				else:
					raw_offset = data.get( 'rawOffset', 0 ) or 0
					dst_offset = data.get( 'dstOffset', 0 ) or 0
					offset_value = round((float( raw_offset ) + float( dst_offset ))/3600.0, 3)
					self.offset = offset_value
					item[ 'timeZoneId' ] = data.get( 'timeZoneId' )
					item[ 'timeZoneName' ] = data.get( 'timeZoneName' )
					item[ 'rawOffset' ] = raw_offset
					item[ 'dstOffset' ] = dst_offset
					item[ 'offset_hours' ] = self.offset
					item[ 'timezone_status' ] = data.get( 'status', 'OK' )
					item[ 'timezone_error' ] = None

			except Exception as row_error:
				item[ 'timeZoneId' ] = None
				item[ 'timeZoneName' ] = None
				item[ 'rawOffset' ] = None
				item[ 'dstOffset' ] = None
				item[ 'offset_hours' ] = None
				item[ 'timezone_status' ] = 'error'
				item[ 'timezone_error' ] = str( row_error )
			output.append( item )
		return output

	except Exception as e:
		exception = Error( e )
		exception.module = 'mapping'
		exception.cause = 'Timezone'
		exception.method = "batch_lookup( self, **args ) -> list"
		raise exception