function parse_date
Parses a date string in YYYY-MM-DD format into a datetime object, returning None if parsing fails or input is empty.
/tf/active/vicechatdev/CDocs/utils/__init__.py
49 - 66
simple
Purpose
This function provides safe date parsing with error handling for date strings. It's designed to convert string representations of dates into Python datetime objects while gracefully handling invalid inputs. The function logs warnings for invalid date formats and returns None instead of raising exceptions, making it suitable for data processing pipelines where some date values may be malformed or missing.
Source Code
def parse_date(date_str: str) -> Optional[datetime]:
"""
Parse date string into datetime object.
Args:
date_str: Date string in the format YYYY-MM-DD
Returns:
Datetime object or None if parsing fails
"""
if not date_str:
return None
try:
return datetime.strptime(date_str, DATE_FORMAT)
except ValueError:
logger.warning(f"Invalid date format: {date_str}")
return None
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
date_str |
str | - | positional_or_keyword |
Parameter Details
date_str: A string representing a date in YYYY-MM-DD format (e.g., '2024-01-15'). Can be None or empty string, which will return None. Invalid formats will trigger a warning log and return None rather than raising an exception.
Return Value
Type: Optional[datetime]
Returns an Optional[datetime] - either a datetime.datetime object representing the parsed date (with time set to 00:00:00), or None if the input is empty, None, or cannot be parsed according to the DATE_FORMAT constant. The datetime object will have no timezone information (naive datetime).
Dependencies
loggingdatetime
Required Imports
import logging
from datetime import datetime
from typing import Optional
Usage Example
import logging
from datetime import datetime
from typing import Optional
# Setup required constants and logger
DATE_FORMAT = '%Y-%m-%d'
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.WARNING)
def parse_date(date_str: str) -> Optional[datetime]:
if not date_str:
return None
try:
return datetime.strptime(date_str, DATE_FORMAT)
except ValueError:
logger.warning(f"Invalid date format: {date_str}")
return None
# Example usage
valid_date = parse_date('2024-01-15')
print(valid_date) # Output: 2024-01-15 00:00:00
invalid_date = parse_date('15-01-2024')
print(invalid_date) # Output: None (logs warning)
empty_date = parse_date('')
print(empty_date) # Output: None
none_date = parse_date(None)
print(none_date) # Output: None
Best Practices
- Ensure the DATE_FORMAT constant is defined as '%Y-%m-%d' before using this function
- Configure logging appropriately to capture warning messages for invalid date formats
- Always check for None return value before using the result, as invalid or empty inputs return None
- This function returns naive datetime objects (no timezone info) - consider timezone handling if needed for your use case
- The function uses fail-safe design pattern - it never raises exceptions, making it safe for batch processing
- For production use, consider whether you need to handle additional date formats or if strict YYYY-MM-DD validation is sufficient
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function parse_datetime 80.9% similar
-
function format_date 64.7% similar
-
function format_datetime 63.3% similar
-
function parse_datetime_v1 54.8% similar
-
function from_json 54.2% similar