Skip to main content

A collection of time-related utility functions for Python

Project description

ALT-time-utils

A collection of time-related utility functions for Python applications.

License: MIT Python 3.8+ Code style: black

Features

  • 🌍 UTC-first design: All timestamps are UTC by default with timezone awareness
  • 🔄 Timezone conversions: Easy conversion between UTC and local time
  • 📅 Multiple formats: ISO 8601, file-friendly timestamps, and human-readable durations
  • 🏷️ Type hints: Full type annotations for better IDE support
  • Well tested: 100% test coverage
  • 🚀 Zero dependencies: Uses only Python standard library

Installation

pip install ALT-time-utils

Quick Start

from time_utils import (
    get_utc_timestamp,
    get_utc_timestamp_string,
    format_duration,
    local_to_utc,
    utc_to_local
)

# Get current UTC time
utc_now = get_utc_timestamp()
print(utc_now)  # 2025-01-15 12:30:45.123456+00:00

# Get UTC timestamp as string with 'Z' suffix
utc_string = get_utc_timestamp_string()
print(utc_string)  # 2025-01-15T12:30:45.123456Z

# Convert local time to UTC
from datetime import datetime
local_time = datetime.now()
utc_time = local_to_utc(local_time)

# Format duration in human-readable format
duration = format_duration(3665.5)
print(duration)  # 1h 1m 5.5s

API Reference

Timestamp Functions

get_utc_timestamp() -> datetime

Get the current UTC timestamp with timezone info.

>>> utc_time = get_utc_timestamp()
>>> print(utc_time.tzinfo)
datetime.timezone.utc

get_utc_timestamp_string() -> str

Get the current UTC timestamp as an ISO format string with 'Z' suffix.

>>> timestamp = get_utc_timestamp_string()
>>> print(timestamp)
'2025-01-15T12:30:45.123456Z'

get_local_timestamp() -> datetime

Get the current timestamp in the local timezone.

>>> local_time = get_local_timestamp()
>>> print(local_time.tzinfo)
<DstTzInfo 'America/New_York' EST-1 day, 19:00:00 STD>

Timezone Conversion

local_to_utc(local_dt: datetime) -> datetime

Convert a local datetime to UTC. Handles both naive and timezone-aware datetimes.

>>> from datetime import datetime
>>> local = datetime.now()  # Naive datetime
>>> utc = local_to_utc(local)
>>> print(utc.tzinfo)
datetime.timezone.utc

utc_to_local(utc_dt: datetime) -> datetime

Convert a UTC datetime to local timezone.

>>> from datetime import datetime, timezone
>>> utc = datetime.now(timezone.utc)
>>> local = utc_to_local(utc)
>>> print(local.tzinfo)
<DstTzInfo 'America/New_York' EST-1 day, 19:00:00 STD>

Formatting Functions

get_file_timestamp() -> str

Get timestamp formatted for filenames (YYYYMMDD_HHMMSS).

>>> timestamp = get_file_timestamp()
>>> print(timestamp)
'20250115_123045'

get_date_string() -> str

Get the current date as a string (YYYYMMDD).

>>> date_str = get_date_string()
>>> print(date_str)
'20250115'

get_time_string() -> str

Get the current time as a string (HHMMSS).

>>> time_str = get_time_string()
>>> print(time_str)
'123045'

format_duration(seconds: float) -> str

Format a duration in seconds to a human-readable string.

>>> format_duration(0.123)
'123ms'
>>> format_duration(45.6)
'45.6s'
>>> format_duration(3665.5)
'1h 1m 5.5s'
>>> format_duration(-5)
'0s'

Utility Functions

get_local_timezone_name() -> str

Get the name of the local timezone.

>>> tz_name = get_local_timezone_name()
>>> print(tz_name)
'EST'

get_local_utc_offset() -> str

Get the local timezone's UTC offset as a string.

>>> offset = get_local_utc_offset()
>>> print(offset)
'-05:00'

format_utc_timestamp(dt: datetime) -> str

Format any datetime as UTC ISO string with 'Z' suffix.

>>> from datetime import datetime
>>> dt = datetime.now()
>>> formatted = format_utc_timestamp(dt)
>>> print(formatted)
'2025-01-15T12:30:45.123456Z'

Examples

Working with Log Files

from time_utils import get_file_timestamp, get_date_string
import os

# Create timestamped log file
timestamp = get_file_timestamp()
log_file = f"app_{timestamp}.log"

# Organize logs by date
date_dir = get_date_string()
os.makedirs(f"logs/{date_dir}", exist_ok=True)

Duration Tracking

from time_utils import get_utc_timestamp, format_duration

start_time = get_utc_timestamp()

# ... do some work ...

end_time = get_utc_timestamp()
duration = (end_time - start_time).total_seconds()
print(f"Operation took: {format_duration(duration)}")

Timezone-Aware Operations

from time_utils import local_to_utc, utc_to_local, get_local_utc_offset
from datetime import datetime

# Schedule something in local time, store in UTC
local_scheduled = datetime(2025, 1, 20, 9, 0, 0)  # 9 AM local
utc_scheduled = local_to_utc(local_scheduled)

# Display in user's timezone
user_local = utc_to_local(utc_scheduled)
offset = get_local_utc_offset()
print(f"Meeting at {user_local.strftime('%I:%M %p')} ({offset})")

Development

Setup

# Clone the repository
git clone https://github.com/Avilir/time_utils.git
cd time_utils

# Set up development environment
./scripts/setup_dev.sh

# Or using make
make setup

Running Tests

# Using make
make test

# Using script
./scripts/run_tests.sh

# Or directly with pytest
python -m pytest

Code Quality

# Run all checks
make all

# Individual checks
make lint        # Run linting
make type-check  # Run type checking
make format      # Format code

Building

# Build distributions
make build

# Or using script
./scripts/build.sh

Contributing

Contributions are welcome! Please follow these guidelines:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes with tests
  4. Run make all to ensure quality
  5. Commit your changes (git commit -m 'Add amazing feature')
  6. Push to the branch (git push origin feature/amazing-feature)
  7. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Author

Avi Layani - alayani@redhat.com

Acknowledgments

  • Inspired by the need for consistent time handling across Python projects

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

alt_time_utils-0.1.0.tar.gz (10.1 kB view details)

Uploaded Source

Built Distribution

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

alt_time_utils-0.1.0-py3-none-any.whl (8.2 kB view details)

Uploaded Python 3

File details

Details for the file alt_time_utils-0.1.0.tar.gz.

File metadata

  • Download URL: alt_time_utils-0.1.0.tar.gz
  • Upload date:
  • Size: 10.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for alt_time_utils-0.1.0.tar.gz
Algorithm Hash digest
SHA256 08576cd1cdbb990f3145836aafdf184e024c0b22e4e670b2e2c2cef7835a7332
MD5 bbc514f16651d64da62a9046718f515e
BLAKE2b-256 b5acaa4095ca4c234a76526623d5f16724fd8f19a0867d46253a4b9300d0f09f

See more details on using hashes here.

File details

Details for the file alt_time_utils-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: alt_time_utils-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 8.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for alt_time_utils-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 6b58bd01e9b4a5beb65b39bb54cfc846464d1870505179c793f7ac6444b394e1
MD5 7e66751eeda149ecfb816cc5ea7e7528
BLAKE2b-256 92882c2a0ddb3181c1015b93a37596aba2ae2ad75f8512e6ef6e6eb6dd0f64fe

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