Skip to main content

Microsoft Azure Maps timezone Client Library for Python

Project description

Azure Maps Timezone Package client library for Python

This package contains a Python SDK for Azure Maps Services for Timezone. Read more about Azure Maps Services here

Source code | API reference documentation | Product documentation

Disclaimer

Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to https://github.com/Azure/azure-sdk-for-python/issues/20691

Getting started

Prerequisites

If you use Azure CLI, replace <resource-group-name> and <account-name> of your choice, and select a proper pricing tier based on your needs via the <sku-name> parameter. Please refer to this page for more details.

az maps account create --resource-group <resource-group-name> --account-name <account-name> --sku <sku-name>

Install the package

Install the Azure Maps Service Timezone SDK.

pip install azure-maps-timezone

Create and Authenticate the MapsTimeZoneClient

To create a client object to access the Azure Maps Timezone API, you will need a credential object. Azure Maps Timezone client also support three ways to authenticate.

1. Authenticate with a Subscription Key Credential

You can authenticate with your Azure Maps Subscription Key. Once the Azure Maps Subscription Key is created, set the value of the key as environment variable: AZURE_SUBSCRIPTION_KEY. Then pass an AZURE_SUBSCRIPTION_KEY as the credential parameter into an instance of AzureKeyCredential.

import os

from azure.core.credentials import AzureKeyCredential
from azure.maps.timezone import MapsTimeZoneClient

credential = AzureKeyCredential(os.environ.get("AZURE_SUBSCRIPTION_KEY"))

timezone_client = MapsTimeZoneClient(
    credential=credential,
)

2. Authenticate with a SAS Credential

Shared access signature (SAS) tokens are authentication tokens created using the JSON Web token (JWT) format and are cryptographically signed to prove authentication for an application to the Azure Maps REST API.

To authenticate with a SAS token in Python, you'll need to generate one using the azure-mgmt-maps package.

We need to tell user to install azure-mgmt-maps: pip install azure-mgmt-maps

Here's how you can generate the SAS token using the list_sas method from azure-mgmt-maps:

from azure.identity import DefaultAzureCredential
from azure.mgmt.maps import AzureMapsManagementClient

"""
# PREREQUISITES
    pip install azure-identity
    pip install azure-mgmt-maps
# USAGE
    python account_list_sas.py

    Before run the sample, please set the values of the client ID, tenant ID and client secret
    of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
    AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
    https://learn.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""


def main():
    client = AzureMapsManagementClient(
        credential=DefaultAzureCredential(),
        subscription_id="your-subscription-id",
    )

    response = client.accounts.list_sas(
        resource_group_name="myResourceGroup",
        account_name="myMapsAccount",
        maps_account_sas_parameters={
            "expiry": "2017-05-24T11:42:03.1567373Z",
            "maxRatePerSecond": 500,
            "principalId": "your-principal-id",
            "regions": ["eastus"],
            "signingKey": "primaryKey",
            "start": "2017-05-24T10:42:03.1567373Z",
        },
    )
    print(response)

Once the SAS token is created, set the value of the token as environment variable: AZURE_SAS_TOKEN. Then pass an AZURE_SAS_TOKEN as the credential parameter into an instance of AzureSasCredential.

import os

from azure.core.credentials import AzureSASCredential
from azure.maps.timezone import MapsTimeZoneClient

credential = AzureSASCredential(os.environ.get("AZURE_SAS_TOKEN"))

timezone_client = MapsTimeZoneClient(
    credential=credential,
)

3. Authenticate with an Microsoft Entra ID credential

You can authenticate with Microsoft Entra ID credential using the Azure Identity library. Authentication by using Microsoft Entra ID requires some initial setup:

After setup, you can choose which type of credential from azure.identity to use. As an example, DefaultAzureCredential can be used to authenticate the client:

Next, set the values of the client ID, tenant ID, and client secret of the Microsoft Entra ID application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET

You will also need to specify the Azure Maps resource you intend to use by specifying the clientId in the client options. The Azure Maps resource client id can be found in the Authentication sections in the Azure Maps resource. Please refer to the documentation on how to find it.

import os
from azure.maps.timezone import MapsTimeZoneClient
from azure.identity import DefaultAzureCredential

credential = DefaultAzureCredential()
timezone_client = MapsTimeZoneClient(credential=credential)

Key concepts

The Azure Maps Timezone client library for Python allows you to interact with each of the components through the use of a dedicated client object.

Sync Clients

MapsTimeZoneClient is the primary client for developers using the Azure Maps Timezone client library for Python. Once you initialized a MapsTimeZoneClient class, you can explore the methods on this client object to understand the different features of the Azure Maps Timezone service that you can access.

Async Clients

This library includes a complete async API supported on Python 3.8+. To use it, you must first install an async transport, such as aiohttp. See azure-core documentation for more information.

Async clients and credentials should be closed when they're no longer needed. These objects are async context managers and define async close methods.

Examples

The following sections provide several code snippets covering some of the most common Azure Maps Timezone tasks, including:

Get timezone by id

This API returns current, historical, and future time zone information for the specified IANA time zone ID.

import os

from azure.core.exceptions import HttpResponseError

subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY", "your subscription key")

def get_timezone_by_id():
    from azure.core.credentials import AzureKeyCredential
    from azure.maps.timezone import MapsTimeZoneClient

    timezone_client = MapsTimeZoneClient(credential=AzureKeyCredential(subscription_key))
    try:
        result = timezone_client.get_timezone_by_id(timezone_id="sr-Latn-RS")
        print(result)
    except HttpResponseError as exception:
        if exception.error is not None:
            print(f"Error Code: {exception.error.code}")
            print(f"Message: {exception.error.message}")

if __name__ == '__main__':
    get_timezone_by_id()

Get timezone by coordinates

This API returns current, historical, and future time zone information for a specified latitude-longitude pair.

import os

from azure.core.exceptions import HttpResponseError

subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY", "your subscription key")

def get_timezone_by_coordinates():
    from azure.core.credentials import AzureKeyCredential
    from azure.maps.timezone import MapsTimeZoneClient

    timezone_client = MapsTimeZoneClient(credential=AzureKeyCredential(subscription_key))
    try:
        result = timezone_client.get_timezone_by_coordinates(coordinates=[25.0338053, 121.5640089])
        print(result)
    except HttpResponseError as exception:
        if exception.error is not None:
            print(f"Error Code: {exception.error.code}")
            print(f"Message: {exception.error.message}")

if __name__ == '__main__':
    get_timezone_by_coordinates()

Get iana version

This API returns the current IANA version number as Metadata.

import os

from azure.core.exceptions import HttpResponseError

subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY", "your subscription key")

def get_iana_version():
    from azure.core.credentials import AzureKeyCredential
    from azure.maps.timezone import MapsTimeZoneClient

    timezone_client = MapsTimeZoneClient(credential=AzureKeyCredential(subscription_key))
    try:
        result = timezone_client.get_iana_version()
        print(result)
    except HttpResponseError as exception:
        if exception.error is not None:
            print(f"Error Code: {exception.error.code}")
            print(f"Message: {exception.error.message}")

if __name__ == '__main__':
    get_iana_version()

Get iana timezone ids

This API returns a full list of IANA time zone IDs. Updates to the IANA service will be reflected in the system within one day.

import os

from azure.core.exceptions import HttpResponseError

subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY", "your subscription key")

def get_iana_timezone_ids():
    from azure.core.credentials import AzureKeyCredential
    from azure.maps.timezone import MapsTimeZoneClient

    timezone_client = MapsTimeZoneClient(credential=AzureKeyCredential(subscription_key))
    try:
        result = timezone_client.get_iana_timezone_ids()
        print(result)
    except HttpResponseError as exception:
        if exception.error is not None:
            print(f"Error Code: {exception.error.code}")
            print(f"Message: {exception.error.message}")

if __name__ == '__main__':
    get_iana_timezone_ids()

Get windows timezone ids

This API returns a full list of Windows time zone IDs.

import os

from azure.core.exceptions import HttpResponseError

subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY", "your subscription key")

def get_windows_timezone_ids():
    from azure.core.credentials import AzureKeyCredential
    from azure.maps.timezone import MapsTimeZoneClient

    timezone_client = MapsTimeZoneClient(credential=AzureKeyCredential(subscription_key))
    try:
        result = timezone_client.get_windows_timezone_ids()
        print(result)
    except HttpResponseError as exception:
        if exception.error is not None:
            print(f"Error Code: {exception.error.code}")
            print(f"Message: {exception.error.message}")

if __name__ == '__main__':
    get_windows_timezone_ids()

Convert windows timezone to iana

This API returns a corresponding IANA ID, given a valid Windows Time Zone ID.

import os

from azure.core.exceptions import HttpResponseError

subscription_key = os.getenv("AZURE_SUBSCRIPTION_KEY", "your subscription key")

def convert_windows_timezone_to_iana():
    from azure.core.credentials import AzureKeyCredential
    from azure.maps.timezone import MapsTimeZoneClient

    timezone_client = MapsTimeZoneClient(credential=AzureKeyCredential(subscription_key))
    try:
        result = timezone_client.convert_windows_timezone_to_iana(windows_timezone_id="Pacific Standard Time")
        print(result)
    except HttpResponseError as exception:
        if exception.error is not None:
            print(f"Error Code: {exception.error.code}")
            print(f"Message: {exception.error.message}")

if __name__ == '__main__':
    convert_windows_timezone_to_iana()

Troubleshooting

General

Maps Timezone clients raise exceptions defined in Azure Core.

This list can be used for reference to catch thrown exceptions. To get the specific error code of the exception, use the error_code attribute, i.e, exception.error_code.

Logging

This library uses the standard logging library for logging. Basic information about HTTP sessions (URLs, headers, etc.) is logged at INFO level.

Detailed DEBUG level logging, including request/response bodies and unredacted headers, can be enabled on a client with the logging_enable argument:

import sys
import logging

# Create a logger for the 'azure.maps.timezone' SDK
logger = logging.getLogger('azure.maps.timezone')
logger.setLevel(logging.DEBUG)

# Configure a console output
handler = logging.StreamHandler(stream=sys.stdout)
logger.addHandler(handler)

Similarly, logging_enable can enable detailed logging for a single operation, even when it isn't enabled for the client:

service_client.get_service_stats(logging_enable=True)

Additional

Still running into issues? If you encounter any bugs or have suggestions, please file an issue in the Issues section of the project.

Next steps

More sample code

Get started with our Maps Timezone samples (Async Version samples).

Several Azure Maps Timezone Python SDK samples are available to you in the SDK's GitHub repository. These samples provide example code for additional scenarios commonly encountered while working with Maps Timezone

set AZURE_SUBSCRIPTION_KEY="<RealSubscriptionKey>"

pip install azure-maps-timezone --pre

python samples/get_timezone_by_id.py
python sample/get_timezone_by_coordinates.py
python samples/get_iana_version.py
python samples/get_iana_timezone_ids.py
python samples/get_windows_timezone_ids.py
python samples/convert_windows_timezone_to_iana.py

Notes: --pre flag can be optionally added, it is to include pre-release and development versions for pip install. By default, pip only finds stable versions.

Further detail please refer to Samples Introduction

Additional documentation

For more extensive documentation on Azure Maps Timezone, see the Azure Maps Timezone documentation on learn.microsoft.com.

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.

Release History

1.0.0b1 (2025-02-10)

Features Added

  • Initial release

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

azure_maps_timezone-1.0.0b1.tar.gz (48.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

azure_maps_timezone-1.0.0b1-py3-none-any.whl (47.7 kB view details)

Uploaded Python 3

File details

Details for the file azure_maps_timezone-1.0.0b1.tar.gz.

File metadata

  • Download URL: azure_maps_timezone-1.0.0b1.tar.gz
  • Upload date:
  • Size: 48.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: RestSharp/106.13.0.0

File hashes

Hashes for azure_maps_timezone-1.0.0b1.tar.gz
Algorithm Hash digest
SHA256 6f096880a2bd7764fd2f43c6de1a29662bd51d41d60a273c0028aaecb2938c3d
MD5 efee3c9d592c4b0f8f0e7bb9da8615d3
BLAKE2b-256 994ea0d88e3fae2c32f75eb6a7b612df6ded9abff5ac4dd80f0b715f8b45be79

See more details on using hashes here.

File details

Details for the file azure_maps_timezone-1.0.0b1-py3-none-any.whl.

File metadata

File hashes

Hashes for azure_maps_timezone-1.0.0b1-py3-none-any.whl
Algorithm Hash digest
SHA256 2eb24ac36e145687bbc0990c3755eebfae00c318bd49688aa52ef7d7b92bf7af
MD5 c2018cfb27d99b8570eb2d5b53cdfbf5
BLAKE2b-256 350b3bcf028982faa1a34afc71de92c99829a55177b764e97ac54dd4daf88a24

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page