Skip to main content

A modern timezone toolkit for Python (microservices) fastapi, starlette

Project description

tz-kit

Django-manered timezone handling for Python microservices (FastAPI/Starlette). A modern, zoneinfo-based toolkit.

Core Philosophy

  1. UTC is the language of systems. Everything stored in the database or passed between services is in UTC.
  2. Local time is the language of users. The system accepts and provides time in the user's preferred timezone at the edge (middleware).

How it Works

The package follows a "Set and Forget" architectural pattern:

  1. Extraction: TimezoneMiddleware intercepts every incoming request and looks for the X-Timezone header (e.g., Asia/Kolkata).
  2. Contextualization: It sets this timezone in an async-safe ContextVar. This ensures that even in highly concurrent environments, each request runs in its own timezone "bubble".
  3. Normalization: When a Pydantic model uses the LocalDateTime type, it automatically detects:
    • Naive datetimes: Converted from the request's timezone to UTC.
    • Time-only strings/objects (e.g., "10:30"): Anchored to today in the request's timezone and converted to UTC.
    • Flexible Formats: Handles non-standard separators like 2026:01:10 10:56 or 2026/01/10.
    • ISO datetimes: Normalized to UTC.

Request Flow Overview

graph TD
    A[Client Request] -->|X-Timezone: Asia/Kolkata| B(TimezoneMiddleware)
    B -->|set_timezone| C{ContextVar}
    C --> D[Business Logic / Pydantic Models]
    D -->|LocalDateTime Validator| E[Normalized UTC Datetime]
    E -->|Store| F[(Database / UTC)]

    style B fill:#f9f,stroke:#333Internal
    style C fill:#bbf,stroke:#333Context
    style E fill:#bfb,stroke:#333UTC

Key Features

  • Modern Python: Built on zoneinfo (PEP 615).
  • Pydantic Integration: Seamlessly handles timezone conversion in request schemas.
  • Async Ready: Uses ContextVar for thread-safe/async-safe context management.
  • Microservices Ready: Optimized for the X-Timezone header standard.
  • Industry Grade: Handles DST gaps/overlaps and extreme dates correctly.

Installation

pip install -r requirements.txt

From GitHub (For other microservices)

To use this package in other services without publishing to PyPI, install directly from git:

pip install git+https://github.com/StartUp-Software-Pvt-Ltd/common-timezone.git

Note: Replace the URL with your actual repository URL.

Quick Start

1. Register Middleware

from fastapi import FastAPI
from tz_kit import TimezoneMiddleware

app = FastAPI()
app.add_middleware(TimezoneMiddleware)

2. Use LocalDateTime in Models

from pydantic import BaseModel
from tz_kit import LocalDateTime

class AppointmentSchema(BaseModel):
    start_time: LocalDateTime # Automatically converts naive inputs to UTC

3. Manual Conversion Helpers

from tz_kit import utc_to_local, local_to_utc

# Manual conversion when needed
local_time = utc_to_local(utc_datetime)

Validation Modes

  • Lenient (Default): If an invalid timezone is provided, the system falls back to UTC to ensure production availability.
  • Strict: Use set_timezone(tz, strict=True) for internal tasks or validation to raise an InvalidTimezoneError.

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

tz_kit-1.0.0.tar.gz (9.4 kB view details)

Uploaded Source

Built Distribution

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

tz_kit-1.0.0-py3-none-any.whl (7.2 kB view details)

Uploaded Python 3

File details

Details for the file tz_kit-1.0.0.tar.gz.

File metadata

  • Download URL: tz_kit-1.0.0.tar.gz
  • Upload date:
  • Size: 9.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.10

File hashes

Hashes for tz_kit-1.0.0.tar.gz
Algorithm Hash digest
SHA256 dae1d4d58835a904769600aebadde5094628092e0497c9e0ca18a11130d24e31
MD5 9841ab01db995045f5984630a0d1df8d
BLAKE2b-256 14f2476b21c764de6fb1b69b0c3f1e3dbee4d7b259b604a3e4a736a632bd09b5

See more details on using hashes here.

File details

Details for the file tz_kit-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: tz_kit-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 7.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.10

File hashes

Hashes for tz_kit-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 0d1e65fe1597675bddbb4c1f147561e01e71fc722b792ee4363644758e9e0f91
MD5 81c73bc8435dca64843f93cb746abc22
BLAKE2b-256 6b2303443a2a40a235c8459abd333d634f8c9cd05b22d1773e617718da75ac20

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