🔍 Code Extractor

function format_datetime_v1

Maturity: 35

Converts an ISO format datetime string into a human-readable UTC datetime string formatted as 'YYYY-MM-DD HH:MM:SS UTC'.

File:
/tf/active/vicechatdev/SPFCsync/dry_run_test.py
Lines:
30 - 38
Complexity:
simple

Purpose

This utility function standardizes datetime string formatting for display purposes. It handles ISO format datetime strings (including those with 'Z' timezone indicator), converts them to datetime objects, and returns a consistently formatted string. If the input is empty or parsing fails, it returns a fallback value ('Unknown' or the original string). This is useful for presenting timestamps in user interfaces or logs with consistent formatting.

Source Code

def format_datetime(dt_str):
    """Format datetime string for display"""
    if not dt_str:
        return "Unknown"
    try:
        dt = datetime.fromisoformat(dt_str.replace('Z', '+00:00'))
        return dt.strftime('%Y-%m-%d %H:%M:%S UTC')
    except:
        return dt_str

Parameters

Name Type Default Kind
dt_str - - positional_or_keyword

Parameter Details

dt_str: A datetime string in ISO format (e.g., '2024-01-15T10:30:00Z' or '2024-01-15T10:30:00+00:00'). Can be None or empty string, which will return 'Unknown'. The function specifically handles the 'Z' timezone indicator by replacing it with '+00:00' for proper parsing.

Return Value

Returns a string in the format 'YYYY-MM-DD HH:MM:SS UTC' (e.g., '2024-01-15 10:30:00 UTC') if parsing is successful. Returns 'Unknown' if dt_str is None, empty string, or falsy. Returns the original dt_str unchanged if datetime parsing fails for any other reason.

Dependencies

  • datetime

Required Imports

from datetime import datetime

Usage Example

from datetime import datetime

def format_datetime(dt_str):
    """Format datetime string for display"""
    if not dt_str:
        return "Unknown"
    try:
        dt = datetime.fromisoformat(dt_str.replace('Z', '+00:00'))
        return dt.strftime('%Y-%m-%d %H:%M:%S UTC')
    except:
        return dt_str

# Example usage:
iso_string = '2024-01-15T10:30:00Z'
formatted = format_datetime(iso_string)
print(formatted)  # Output: 2024-01-15 10:30:00 UTC

# Handle empty input
print(format_datetime(None))  # Output: Unknown
print(format_datetime(''))    # Output: Unknown

# Handle invalid format
print(format_datetime('invalid-date'))  # Output: invalid-date

Best Practices

  • The function uses a bare except clause which catches all exceptions. Consider catching specific exceptions (ValueError, AttributeError) for better error handling and debugging.
  • The function assumes all datetime strings should be displayed in UTC. If timezone-aware display is needed, this function would need modification.
  • The 'Z' to '+00:00' replacement handles Zulu time notation, but the function doesn't validate if the input is actually in UTC before labeling it as such.
  • For production use, consider logging parsing failures instead of silently returning the original string.
  • The function returns different types of fallback values (string 'Unknown' vs original string) which could make error handling inconsistent for callers.

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function format_datetime 62.2% similar

    Formats a datetime object into a standardized string representation for display purposes, returning an empty string if the input is None.

    From: /tf/active/vicechatdev/CDocs/utils/__init__.py
  • function dt_to_int 57.8% similar

    Converts various datetime types (pandas, numpy, cftime, Python datetime) to an integer timestamp with a specified time unit.

    From: /tf/active/vicechatdev/patches/util.py
  • function format_date 56.2% similar

    Formats a datetime object into a string representation according to a predefined DATE_FORMAT constant, returning an empty string if the input is None.

    From: /tf/active/vicechatdev/CDocs/utils/__init__.py
  • function parse_datetime_v1 56.1% similar

    Converts various date representations (string, integer, pandas Timestamp) into a numpy datetime64 object using pandas datetime parsing capabilities.

    From: /tf/active/vicechatdev/patches/util.py
  • function parse_datetime_selection 53.2% similar

    Converts string or datetime-like selection specifications into parsed datetime objects, handling single values, slices, and collections.

    From: /tf/active/vicechatdev/patches/util.py
← Back to Browse