🔍 Code Extractor

function format_date

Maturity: 53

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

File:
/tf/active/vicechatdev/CDocs/utils/__init__.py
Lines:
21 - 33
Complexity:
simple

Purpose

This utility function provides consistent date formatting across the application for display purposes. It handles None values gracefully by returning an empty string, making it safe to use in contexts where dates may be optional or missing. The function is designed to standardize date presentation in user interfaces, reports, or any output where dates need to be displayed in a uniform format.

Source Code

def format_date(date_obj: Optional[datetime]) -> str:
    """
    Format date for display.
    
    Args:
        date_obj: Date to format
        
    Returns:
        Formatted date string or empty string if None
    """
    if date_obj is None:
        return ""
    return date_obj.strftime(DATE_FORMAT)

Parameters

Name Type Default Kind
date_obj Optional[datetime] - positional_or_keyword

Parameter Details

date_obj: An optional datetime object to be formatted. Can be None, in which case the function returns an empty string. When provided, it should be a valid datetime instance that will be formatted according to the DATE_FORMAT constant defined elsewhere in the codebase.

Return Value

Type: str

Returns a string representation of the formatted date. If date_obj is None, returns an empty string (''). If date_obj is a valid datetime object, returns the date formatted according to the DATE_FORMAT constant using strftime(). The exact format depends on the DATE_FORMAT constant definition (e.g., 'YYYY-MM-DD', 'MM/DD/YYYY', etc.).

Dependencies

  • datetime

Required Imports

from datetime import datetime
from typing import Optional

Usage Example

from datetime import datetime
from typing import Optional

# Define DATE_FORMAT constant (required)
DATE_FORMAT = '%Y-%m-%d'

def format_date(date_obj: Optional[datetime]) -> str:
    if date_obj is None:
        return ""
    return date_obj.strftime(DATE_FORMAT)

# Example usage
today = datetime(2024, 1, 15, 10, 30, 0)
formatted = format_date(today)
print(formatted)  # Output: '2024-01-15'

# Handle None case
no_date = format_date(None)
print(no_date)  # Output: ''

# Use with current datetime
current = datetime.now()
formatted_current = format_date(current)
print(formatted_current)  # Output: current date in YYYY-MM-DD format

Best Practices

  • Ensure DATE_FORMAT constant is defined before calling this function, otherwise a NameError will occur
  • The DATE_FORMAT should be a valid strftime format string to avoid runtime errors
  • This function is safe for use with None values, making it ideal for optional date fields
  • Consider the locale and timezone implications when displaying dates to users
  • For internationalization, consider using locale-aware formatting or passing the format as a parameter
  • The function does not perform timezone conversion; ensure datetime objects are in the desired timezone before formatting
  • For more complex date formatting needs (e.g., relative dates, localization), consider using libraries like babel or arrow

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function format_datetime 95.1% 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 parse_date 64.7% similar

    Parses a date string in YYYY-MM-DD format into a datetime object, returning None if parsing fails or input is empty.

    From: /tf/active/vicechatdev/CDocs/utils/__init__.py
  • function format_datetime_v1 56.2% similar

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

    From: /tf/active/vicechatdev/SPFCsync/dry_run_test.py
  • function parse_datetime 51.5% similar

    Parses a datetime string in YYYY-MM-DD HH:MM:SS format into a Python datetime object, returning None if parsing fails.

    From: /tf/active/vicechatdev/CDocs/utils/__init__.py
  • function safe_json_serialize 44.7% similar

    Recursively converts Python objects into JSON-serializable formats, with special handling for datetime objects and objects with to_dict() methods.

    From: /tf/active/vicechatdev/CDocs/utils/__init__.py
← Back to Browse