""" Temporal data parsing and normalization. Handles inconsistent date/time formats across 20 years of data, including filename dates, timestamp strings, and timezone handling. """ from pathlib import Path from typing import Optional, List, Tuple from datetime import datetime import re import pytz from dateutil import parser as dateutil_parser from ..core.base_classes import BaseCleaner from ..core.config import Config from ..core.errata_logger import ErrataLogger from ..core.exceptions import TemporalError class TemporalParser(BaseCleaner): """ Parses and normalizes temporal data. Handles: - Multiple date/time formats - Timezone normalization - Filename date extraction - Validation against reasonable date ranges """ def __init__(self, config: Config, errata_logger: Optional[ErrataLogger] = None): """ Initialize temporal parser. Args: config: Configuration object errata_logger: Optional errata logger for error tracking """ super().__init__(config, errata_logger) # Get configuration self.date_formats: List[str] = config.get( 'temporal.date_formats', [ '%a %b %d %H:%M:%S %Y', '%Y-%m-%d %H:%M:%S', '%m/%d/%Y %H:%M:%S', '%Y%m%d' ] ) from datetime import datetime as _dt self.min_year: int = config.get('temporal.min_year', 2000) self.max_year: int = config.get('temporal.max_year', _dt.now().year) self.timezone_name: str = config.get('temporal.timezone', 'America/Los_Angeles') try: self.timezone = pytz.timezone(self.timezone_name) except pytz.exceptions.UnknownTimeZoneError: self.timezone = pytz.UTC def parse_date( self, date_string: str, file_path: Optional[str] = None ) -> Optional[datetime]: """ Parse date string into datetime object. Tries multiple formats in sequence. Args: date_string: Date string to parse file_path: Optional file path for error logging Returns: datetime object or None if parsing fails """ if not date_string or not isinstance(date_string, str): return None date_string = date_string.strip() # Handle empty/null strings if date_string.lower() in ('nan', 'none', 'null', ''): return None # Reject values too short to be a date (e.g. "1", "0", "+2.24") if len(date_string) < 6: return None # Skip obvious non-date values (file paths, URLs, etc.) if any(indicator in date_string.lower() for indicator in ['.jpg', '.png', '.gif', '.dat', '/', '\\']): # Check if it contains common path separators or file extensions if '/' in date_string or '\\' in date_string or date_string.lower().endswith(('.jpg', '.png', '.gif', '.dat', '.txt', '.csv')): return None # Convert underscores to spaces (Thu_Dec_20_00:13:03_2018 -> Thu Dec 20 00:13:03 2018) date_string = date_string.replace('_', ' ') # Apply year correction patterns before parsing date_string = self._correct_year_typos(date_string, file_path) # Try configured formats first for fmt in self.date_formats: try: dt = datetime.strptime(date_string, fmt) return self._validate_and_localize(dt, file_path) except (ValueError, TemporalError): continue # Try dateutil parser as fallback (more flexible) # Use a fixed default date so we can detect when dateutil guessed the year _sentinel = datetime(1, 1, 1) try: dt = dateutil_parser.parse(date_string, default=_sentinel) if dt.year == 1: # dateutil filled in the sentinel year — input had no year self.log_error( 'date_parse_failed', f"Incomplete date (no year): '{date_string}'", file_path=file_path ) return None return self._validate_and_localize(dt, file_path) except (ValueError, TemporalError, dateutil_parser.ParserError): pass # All parsing attempts failed self.log_error( 'date_parse_failed', f"Could not parse date: '{date_string}'", file_path=file_path ) return None def _correct_year_typos( self, date_string: str, file_path: Optional[str] = None ) -> str: """ Correct common year typos in date strings. Common patterns: - 0202 -> 2002 (leading 2 dropped) Args: date_string: Date string to correct file_path: Optional file path for error logging Returns: Corrected date string """ # Pattern: Year 0202 -> 2002 (leading 2 dropped) # Anchor to word boundary so we only match standalone year tokens, # not substrings inside coordinates or other numeric fields. year_pattern = r'\b0(20[0-2])\b' if re.search(year_pattern, date_string): original = date_string date_string = re.sub(year_pattern, r'2\1', date_string) self.log_error( 'year_corrected', f"Corrected year 0xxx -> 2xxx: '{original}' -> '{date_string}'", file_path=file_path ) # Pattern: Year in format like "Sep 04 0202" # Only replace when the typo year appears at the END of the string # (i.e. in year position), not in the middle of other data. end_year_match = re.search(r'\b(0202|0201|0200)$', date_string) if end_year_match: year_corrections = { '0202': '2002', '0201': '2001', '0200': '2000', } typo = end_year_match.group(1) correct = year_corrections[typo] original = date_string date_string = date_string[:end_year_match.start()] + correct + date_string[end_year_match.end():] self.log_error( 'year_corrected', f"Corrected trailing year {typo} -> {correct}: '{original}' -> '{date_string}'", file_path=file_path ) return date_string def _validate_and_localize( self, dt: datetime, file_path: Optional[str] = None ) -> datetime: """ Validate datetime is in reasonable range and localize to timezone. Args: dt: datetime to validate file_path: Optional file path for error logging Returns: Validated and localized datetime Raises: TemporalError: If date is out of valid range """ # Check year range if dt.year < self.min_year or dt.year > self.max_year: self.log_error( 'date_out_of_range', f"Date {dt} outside valid range ({self.min_year}-{self.max_year})", file_path=file_path ) raise TemporalError(f"Date out of range: {dt}") # Localize to timezone if naive if dt.tzinfo is None: dt = self.timezone.localize(dt) else: # Convert to target timezone dt = dt.astimezone(self.timezone) return dt def parse_dates_vectorized( self, series: 'pd.Series', file_path: Optional[str] = None ) -> 'pd.Series': """ Parse a Series of date strings vectorized, with per-row fallback. Uses pd.to_datetime with the primary format first (5x faster than per-row .apply), then falls back to parse_date() for any failures. Args: series: Series of date strings file_path: Optional file path for error logging Returns: Series of parsed datetime objects (timezone-aware) """ import pandas as pd # Strip whitespace cleaned = series.astype(str).str.strip() # Replace underscores (Thu_Dec_20_00:13:03_2018 -> Thu Dec 20 00:13:03 2018) cleaned = cleaned.str.replace('_', ' ', regex=False) # Try primary format vectorized (covers ~99% of timestamps) primary_fmt = self.date_formats[0] if self.date_formats else '%a %b %d %H:%M:%S %Y' result = pd.to_datetime(cleaned, format=primary_fmt, errors='coerce') # Localize to timezone (always, so result dtype is tz-aware for fallback assignment) successful = result.notna() # ambiguous=False: during DST fall-back, pick standard time rather than # nulling the timestamp (the old 'NaT' policy silently dropped ~1 hour of # data per year). nonexistent='shift_forward': spring-forward gaps get # shifted to the next valid instant instead of becoming NaT. result = result.dt.tz_localize(self.timezone, ambiguous=False, nonexistent='shift_forward') # Validate year range on successful parses if successful.any(): out_of_range = successful & ( (result.dt.year < self.min_year) | (result.dt.year > self.max_year) ) if out_of_range.any(): result[out_of_range] = pd.NaT # Fall back to per-row parsing for failures failed = result.isna() & cleaned.notna() & (cleaned != 'nan') & (cleaned != '') if failed.any(): import warnings with warnings.catch_warnings(): warnings.simplefilter('ignore') fallback = cleaned[failed].apply( lambda x: self.parse_date(x, file_path=file_path) ) fallback = pd.to_datetime(fallback, utc=True).dt.tz_convert(self.timezone) result = result.copy() result.loc[failed] = fallback return result def extract_date_from_filename( self, filename: str, pattern: Optional[str] = None ) -> Optional[datetime]: """ Extract date from filename using pattern. Default pattern matches formats like: cardD010102.dat (YYMMDD) Args: filename: Filename to extract date from pattern: Optional regex pattern (defaults to YYMMDD) Returns: datetime object or None if extraction fails """ if pattern is None: # Default pattern: 6 digits representing YYMMDD pattern = r'(\d{6})' match = re.search(pattern, filename) if not match: return None date_str = match.group(1) # Parse YYMMDD format if len(date_str) == 6: try: yy = int(date_str[0:2]) mm = int(date_str[2:4]) dd = int(date_str[4:6]) # Assume 20xx for YY year = 2000 + yy dt = datetime(year, mm, dd) return self._validate_and_localize(dt) except (ValueError, TemporalError): return None # Try other date string parsing return self.parse_date(date_str) def clean( self, data: str, file_path: Optional[str] = None, **kwargs ) -> Optional[datetime]: """ Parse date string into normalized datetime. Args: data: Date string to parse file_path: Optional file path for error logging **kwargs: Additional parameters Returns: datetime object or None if parsing fails """ return self.parse_date(data, file_path=file_path) def parse_batch( self, date_strings: List[str], file_path: Optional[str] = None ) -> List[Optional[datetime]]: """ Parse a batch of date strings. Args: date_strings: List of date strings file_path: Optional file path for error logging Returns: List of datetime objects (None for failed parses) """ return [ self.parse_date(ds, file_path=file_path) for ds in date_strings ] def format_datetime( self, dt: datetime, format_str: str = '%Y-%m-%d %H:%M:%S' ) -> str: """ Format datetime to string. Args: dt: datetime object format_str: Output format string Returns: Formatted date string """ return dt.strftime(format_str) def get_date_range( self, datetimes: List[datetime] ) -> Tuple[datetime, datetime]: """ Get min and max dates from list of datetimes. Args: datetimes: List of datetime objects Returns: Tuple of (min_date, max_date) Raises: TemporalError: If list is empty """ valid_dts = [dt for dt in datetimes if dt is not None] if not valid_dts: raise TemporalError("No valid datetimes in list") return min(valid_dts), max(valid_dts)