CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-google-api-core

Google API client core library providing common helpers, utilities, and components for Python client libraries

Pending
Overview
Eval results
Files

datetime.mddocs/

Date/Time Utilities

Utilities for handling datetime objects in Google APIs, including RFC3339 formatting, timezone handling, and high-precision timestamps with nanosecond support.

Capabilities

High-Precision Datetime Class

Extended datetime class with nanosecond precision for Google API timestamps.

class DatetimeWithNanoseconds(datetime.datetime):
    """
    Datetime subclass that adds nanosecond precision.
    
    Args:
        year (int): Year
        month (int): Month (1-12)
        day (int): Day of month (1-31)
        hour (int, optional): Hour (0-23)
        minute (int, optional): Minute (0-59)
        second (int, optional): Second (0-59)
        microsecond (int, optional): Microsecond (0-999999)
        nanosecond (int, optional): Nanosecond component (0-999)
        tzinfo: Timezone information
        **kwargs: Additional datetime arguments
    """
    def __new__(cls, year, month, day, hour=0, minute=0, second=0, microsecond=0, nanosecond=0, tzinfo=None, **kwargs): ...
    
    @property
    def nanosecond(self):
        """
        Nanosecond component (0-999).
        
        Returns:
            int: Nanosecond value
        """
    
    def timestamp(self):
        """
        Get timestamp with nanosecond precision.
        
        Returns:
            float: Timestamp including nanoseconds
        """
    
    def rfc3339(self):
        """
        Format as RFC3339 string with nanosecond precision.
        
        Returns:
            str: RFC3339 formatted timestamp
        """

Time Conversion Functions

Functions for converting between different time representations used in Google APIs.

def utcnow():
    """
    Get current UTC datetime (mockable version of datetime.utcnow).
    
    Returns:
        datetime.datetime: Current UTC datetime
    """

def to_milliseconds(value):
    """
    Convert datetime to milliseconds since Unix epoch.
    
    Args:
        value (datetime.datetime): Datetime to convert
        
    Returns:
        int: Milliseconds since epoch
    """

def from_microseconds(value):
    """
    Convert microseconds since epoch to datetime.
    
    Args:
        value (int): Microseconds since Unix epoch
        
    Returns:
        datetime.datetime: Converted datetime in UTC
    """

def to_microseconds(value):
    """
    Convert datetime to microseconds since Unix epoch.
    
    Args:
        value (datetime.datetime): Datetime to convert
        
    Returns:
        int: Microseconds since epoch
    """

RFC3339 Parsing and Formatting

Functions for parsing and formatting RFC3339 timestamps with timezone support.

def from_rfc3339(value):
    """
    Parse RFC3339 timestamp string to datetime with nanosecond precision.
    
    Args:
        value (str): RFC3339 formatted timestamp string
        
    Returns:
        DatetimeWithNanoseconds: Parsed datetime with nanosecond precision
    """

def to_rfc3339(value, ignore_zone=True):
    """
    Convert datetime to RFC3339 formatted string.
    
    Args:
        value (datetime.datetime): Datetime to format
        ignore_zone (bool): Whether to ignore timezone info (default: True)
        
    Returns:
        str: RFC3339 formatted timestamp string
    """

def from_rfc3339_nanos(value):
    """
    Deprecated alias for from_rfc3339.
    
    Args:
        value (str): RFC3339 formatted timestamp string
        
    Returns:
        DatetimeWithNanoseconds: Parsed datetime
    """

ISO8601 Parsing

Functions for parsing ISO8601 date and time strings.

def from_iso8601_date(value):
    """
    Parse ISO8601 date string to datetime.
    
    Args:
        value (str): ISO8601 date string (YYYY-MM-DD)
        
    Returns:
        datetime.datetime: Parsed date as datetime at midnight UTC
    """

def from_iso8601_time(value):
    """
    Parse ISO8601 time string to datetime.
    
    Args:
        value (str): ISO8601 time string (HH:MM:SS or HH:MM:SS.fff)
        
    Returns:
        datetime.datetime: Parsed time as datetime on epoch date
    """

Usage Examples

Working with Nanosecond Precision

from google.api_core import datetime_helpers
from datetime import datetime, timezone

# Create datetime with nanosecond precision
precise_time = datetime_helpers.DatetimeWithNanoseconds(
    2023, 12, 25, 14, 30, 45, 123456, nanosecond=789,
    tzinfo=timezone.utc
)

print(f"Nanoseconds: {precise_time.nanosecond}")
print(f"RFC3339: {precise_time.rfc3339()}")
print(f"Timestamp: {precise_time.timestamp()}")

# Convert to/from microseconds with nanosecond precision
microseconds = datetime_helpers.to_microseconds(precise_time)
recovered = datetime_helpers.from_microseconds(microseconds)
print(f"Microseconds: {microseconds}")

RFC3339 Timestamp Handling

from google.api_core import datetime_helpers

# Parse RFC3339 timestamps from API responses
api_timestamp = "2023-12-25T14:30:45.123456789Z"
parsed_time = datetime_helpers.from_rfc3339(api_timestamp)

print(f"Parsed time: {parsed_time}")
print(f"Nanoseconds: {parsed_time.nanosecond}")
print(f"Year: {parsed_time.year}")

# Format datetime for API requests
current_time = datetime_helpers.utcnow()
rfc3339_string = datetime_helpers.to_rfc3339(current_time)
print(f"Current time RFC3339: {rfc3339_string}")

# Handle timezone-aware timestamps
timezone_timestamp = "2023-12-25T14:30:45.123-08:00"
parsed_tz = datetime_helpers.from_rfc3339(timezone_timestamp)
print(f"Timezone aware: {parsed_tz}")

API Response Processing

from google.api_core import datetime_helpers
import json

def process_api_response(response_data):
    """Process API response with timestamp fields."""
    processed = {}
    
    for key, value in response_data.items():
        if key.endswith('_time') or key.endswith('_timestamp'):
            # Convert timestamp strings to datetime objects
            if isinstance(value, str):
                try:
                    processed[key] = datetime_helpers.from_rfc3339(value)
                except ValueError:
                    # Fallback for other timestamp formats
                    processed[key] = value
            else:
                processed[key] = value
        else:
            processed[key] = value
    
    return processed

# Example API response
api_response = {
    "id": "123",
    "name": "Resource",
    "created_time": "2023-12-25T14:30:45.123456789Z",
    "updated_time": "2023-12-25T15:45:30.987654321Z",
    "status": "active"
}

processed = process_api_response(api_response)
print(f"Created: {processed['created_time']}")
print(f"Updated: {processed['updated_time']}")

Time Range Queries

from google.api_core import datetime_helpers
from datetime import datetime, timedelta, timezone

def create_time_range_filter(days_back=7):
    """Create time range filter for API queries."""
    now = datetime_helpers.utcnow()
    start_time = now - timedelta(days=days_back)
    
    return {
        "start_time": datetime_helpers.to_rfc3339(start_time),
        "end_time": datetime_helpers.to_rfc3339(now)
    }

# Create filter for last 30 days
time_filter = create_time_range_filter(30)
print(f"Query range: {time_filter['start_time']} to {time_filter['end_time']}")

def query_logs_by_time_range(start_time, end_time):
    """Query logs within time range."""
    request = {
        "filter": f"timestamp >= '{start_time}' AND timestamp <= '{end_time}'",
        "order_by": "timestamp desc"
    }
    
    # Make API call with time range filter
    return request

query = query_logs_by_time_range(
    time_filter["start_time"],
    time_filter["end_time"]
)

Millisecond Precision Operations

from google.api_core import datetime_helpers
import time

# Work with millisecond timestamps (common in APIs)
current_millis = int(time.time() * 1000)
print(f"Current milliseconds: {current_millis}")

# Convert datetime to milliseconds for API calls
now = datetime_helpers.utcnow()
millis = datetime_helpers.to_milliseconds(now)
print(f"Datetime to millis: {millis}")

# Convert API millisecond response back to datetime
api_millis = 1703516245123  # Example from API
dt_from_millis = datetime.utcfromtimestamp(api_millis / 1000.0)
print(f"Millis to datetime: {dt_from_millis}")

# High precision timing
def measure_operation_time():
    """Measure operation with high precision."""
    start = datetime_helpers.utcnow()
    
    # Simulate some operation
    time.sleep(0.1)
    
    end = datetime_helpers.utcnow()
    
    duration_micros = (
        datetime_helpers.to_microseconds(end) - 
        datetime_helpers.to_microseconds(start)
    )
    
    print(f"Operation took {duration_micros} microseconds")
    return duration_micros

measure_operation_time()

Timezone Handling

from google.api_core import datetime_helpers
from datetime import datetime, timezone, timedelta

# Parse timestamps with different timezone formats
timestamps = [
    "2023-12-25T14:30:45Z",           # UTC
    "2023-12-25T14:30:45.123Z",       # UTC with milliseconds
    "2023-12-25T14:30:45+00:00",     # UTC with offset
    "2023-12-25T14:30:45-08:00",     # Pacific Standard Time
    "2023-12-25T14:30:45.123456+05:30"  # India Standard Time with microseconds
]

for ts in timestamps:
    parsed = datetime_helpers.from_rfc3339(ts)
    # Convert to UTC for consistent handling
    utc_time = parsed.replace(tzinfo=timezone.utc) if parsed.tzinfo is None else parsed.astimezone(timezone.utc)
    print(f"Original: {ts}")
    print(f"UTC: {datetime_helpers.to_rfc3339(utc_time)}")
    print("---")

Install with Tessl CLI

npx tessl i tessl/pypi-google-api-core

docs

bidirectional-streaming.md

client-config.md

datetime.md

exceptions.md

gapic-framework.md

iam-policies.md

index.md

operations.md

page-iteration.md

path-templates.md

protobuf-helpers.md

retry.md

timeout.md

transport.md

universe-domain.md

tile.json