function parse_datetime
Parses a datetime string in YYYY-MM-DD HH:MM:SS format into a Python datetime object, returning None if parsing fails.
/tf/active/vicechatdev/CDocs/utils/__init__.py
68 - 85
simple
Purpose
This function provides safe datetime parsing with error handling for the CDocs document management system. It converts string representations of dates and times into datetime objects that can be used for date arithmetic, comparisons, and storage. The function gracefully handles invalid inputs by logging warnings and returning None instead of raising exceptions, making it suitable for processing user input or external data sources where datetime format may be inconsistent.
Source Code
def parse_datetime(datetime_str: str) -> Optional[datetime]:
"""
Parse datetime string into datetime object.
Args:
datetime_str: Datetime string in the format YYYY-MM-DD HH:MM:SS
Returns:
Datetime object or None if parsing fails
"""
if not datetime_str:
return None
try:
return datetime.strptime(datetime_str, DATETIME_FORMAT)
except ValueError:
logger.warning(f"Invalid datetime format: {datetime_str}")
return None
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
datetime_str |
str | - | positional_or_keyword |
Parameter Details
datetime_str: A string representing a date and time in the format 'YYYY-MM-DD HH:MM:SS' (e.g., '2024-01-15 14:30:00'). Can be None or empty string, which will return None. Any other format will trigger a warning log and return None.
Return Value
Type: Optional[datetime]
Returns a datetime.datetime object if parsing succeeds, representing the parsed date and time. Returns None if the input is empty, None, or if the string doesn't match the expected format 'YYYY-MM-DD HH:MM:SS'. The None return allows calling code to handle invalid dates gracefully without exception handling.
Dependencies
loggingdatetime
Required Imports
import logging
from datetime import datetime
from typing import Optional
Usage Example
from datetime import datetime
from typing import Optional
import logging
# Setup required constants and logger
DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.WARNING)
def parse_datetime(datetime_str: str) -> Optional[datetime]:
if not datetime_str:
return None
try:
return datetime.strptime(datetime_str, DATETIME_FORMAT)
except ValueError:
logger.warning(f"Invalid datetime format: {datetime_str}")
return None
# Example usage
valid_date = parse_datetime('2024-01-15 14:30:00')
if valid_date:
print(f"Parsed date: {valid_date}")
print(f"Year: {valid_date.year}, Month: {valid_date.month}")
invalid_date = parse_datetime('2024/01/15 14:30:00')
if invalid_date is None:
print("Failed to parse invalid format")
empty_date = parse_datetime('')
print(f"Empty string result: {empty_date}")
Best Practices
- Always check if the return value is None before using the datetime object to avoid AttributeError
- The function expects the DATETIME_FORMAT constant to be defined at module level with value '%Y-%m-%d %H:%M:%S'
- Ensure a logger is configured before using this function to capture warning messages for invalid formats
- This function is designed for a specific datetime format; for multiple format support, consider using dateutil.parser or extending this function
- The function returns None for both empty strings and invalid formats, so distinguish between these cases if needed by checking the input before calling
- Consider wrapping calls to this function in validation logic if you need to provide user feedback about specific format requirements
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function parse_date 80.9% similar
-
function parse_datetime_v1 60.6% similar
-
function format_datetime 59.1% similar
-
function parse_datetime_selection 57.8% similar
-
function from_json 52.5% similar