| """ |
| 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) |
|
|
| |
| 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() |
|
|
| |
| if date_string.lower() in ('nan', 'none', 'null', ''): |
| return None |
|
|
| |
| if len(date_string) < 6: |
| return None |
|
|
| |
| if any(indicator in date_string.lower() for indicator in ['.jpg', '.png', '.gif', '.dat', '/', '\\']): |
| |
| if '/' in date_string or '\\' in date_string or date_string.lower().endswith(('.jpg', '.png', '.gif', '.dat', '.txt', '.csv')): |
| return None |
|
|
| |
| date_string = date_string.replace('_', ' ') |
|
|
| |
| date_string = self._correct_year_typos(date_string, file_path) |
|
|
| |
| 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 |
|
|
| |
| |
| _sentinel = datetime(1, 1, 1) |
| try: |
| dt = dateutil_parser.parse(date_string, default=_sentinel) |
| if dt.year == 1: |
| |
| 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 |
|
|
| |
| 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 |
| """ |
| |
| |
| |
| 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 |
| ) |
|
|
| |
| |
| |
| 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 |
| """ |
| |
| 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}") |
|
|
| |
| if dt.tzinfo is None: |
| dt = self.timezone.localize(dt) |
| else: |
| |
| 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 |
|
|
| |
| cleaned = series.astype(str).str.strip() |
|
|
| |
| cleaned = cleaned.str.replace('_', ' ', regex=False) |
|
|
| |
| 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') |
|
|
| |
| successful = result.notna() |
| |
| |
| |
| |
| result = result.dt.tz_localize(self.timezone, ambiguous=False, nonexistent='shift_forward') |
|
|
| |
| 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 |
|
|
| |
| 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: |
| |
| pattern = r'(\d{6})' |
|
|
| match = re.search(pattern, filename) |
| if not match: |
| return None |
|
|
| date_str = match.group(1) |
|
|
| |
| if len(date_str) == 6: |
| try: |
| yy = int(date_str[0:2]) |
| mm = int(date_str[2:4]) |
| dd = int(date_str[4:6]) |
|
|
| |
| year = 2000 + yy |
|
|
| dt = datetime(year, mm, dd) |
| return self._validate_and_localize(dt) |
|
|
| except (ValueError, TemporalError): |
| return None |
|
|
| |
| 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) |