Source code for lalandre_core.utils.date_utils
"""
Date Utility Functions
Centralized date formatting and conversion utilities
"""
from datetime import date, datetime
from typing import Any, Optional
[docs]
def to_timestamp(date_value: Any) -> Optional[int]:
"""
Convert a date to Unix timestamp (seconds since epoch)
Handles multiple input types, same like the previous function
Args:
date_value: Date to convert (datetime, date, str, or None)
Returns:
Unix timestamp (int) or None
Examples:
>>> to_timestamp(datetime(2016, 4, 27, 12, 0, 0))
1461758400 # (approximate, depends on timezone)
>>> to_timestamp("2016-04-27")
1461715200
>>> to_timestamp(None)
None
"""
if date_value is None:
return None
try:
# Parse string to datetime if needed
if isinstance(date_value, str):
date_value = datetime.fromisoformat(date_value)
# Convert date to datetime (midnight)
if isinstance(date_value, date) and not isinstance(date_value, datetime):
date_value = datetime.combine(date_value, datetime.min.time())
# Get timestamp
if hasattr(date_value, "timestamp"):
return int(date_value.timestamp())
return None
except (ValueError, AttributeError, TypeError):
# Invalid date format or type
return None
[docs]
def convert_dates_to_strings(props: dict[str, Any], date_fields: list[str]) -> dict[str, Any]:
"""
Convert datetime objects to strings in a dictionary for database storage
Useful for Neo4j, or other databases that require date strings.
Mutates the input dictionary in place.
Args:
props: Dictionary of properties (will be modified)
date_fields: List of field names that contain dates
Returns:
Modified properties dict with dates as ISO format strings
Examples:
>>> data = {'created_at': datetime(2024, 1, 1), 'name': 'Test'}
>>> convert_dates_to_strings(data, ['created_at'])
{'created_at': '2024-01-01T00:00:00', 'name': 'Test'}
"""
for key in date_fields:
if key in props and props[key]:
props[key] = format_date(props[key])
return props