Date Manager
dashboard.src.date_manager
Module de gestion des dates et heures pour les tables ROR.
Classes
DateTimeManager
dataclass
Class to manage date and time operations for ROR tables.
Source code in dashboard/src/date_manager.py
@dataclass
class DateTimeManager:
"""Class to manage date and time operations for ROR tables."""
execution_time: Union[str, datetime]
execution_hour: Optional[int] = None
MONTH_NAMES = {
"01": "Janvier", "02": "Février", "03": "Mars",
"04": "Avril", "05": "Mai", "06": "Juin",
"07": "Juillet", "08": "Août", "09": "Septembre",
"10": "Octobre", "11": "Novembre", "12": "Décembre"
}
DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'
def __post_init__(self):
"""Initialize calculated attributes after instance creation."""
try:
self.execution_time = self._parse_datetime(self.execution_time)
self.execution_hour = self._calculate_execution_hour()
self._initialize_dates()
self._initialize_formats()
logger.info("DateTimeManager initialized successfully")
except Exception as e:
logger.error(f"Error during initialization: {str(e)}")
raise
def _parse_datetime(self, dt_value: Union[str, datetime]) -> datetime:
"""
Parse une chaîne de caractères en datetime.
Args:
dt_value: Valeur datetime à parser
Returns:
Object datetime
"""
if isinstance(dt_value, str):
logger.info(f"Proccesing ETL for {dt_value}")
try:
# Essayer d'abord le format standard
return datetime.strptime(dt_value, self.DATETIME_FORMAT)
except ValueError:
try:
# Essayer avec pendulum si le format standard échoue
return pendulum.parse(dt_value).datetime
except Exception as e:
# Si tout échoue, utiliser datetime.now()
logger.warning(f"Impossible de parser la date {dt_value}, utilisation de datetime.now()")
return datetime.now()
return dt_value
def _calculate_execution_hour(self) -> int:
"""Calculate the execution hour based on current time."""
if self.execution_hour is not None:
return self.execution_hour
current_hour = int(pendulum.instance(self.execution_time)
.in_timezone("Europe/Paris")
.format("H"))
if 11 <= current_hour < 18:
return 11
else:
return 18
def _get_previous_working_day(self) -> datetime:
"""Get the previous working day, accounting for weekends."""
current_date = self.execution_time.date()
if current_date.weekday() == 0: # Monday
return current_date - timedelta(days=3)
return current_date - timedelta(days=1)
def _initialize_dates(self) -> None:
"""Initialize all date-related attributes."""
self.today = self.execution_time.date()
self.prev_day = self._get_previous_working_day()
self.start_date = (self.today - timedelta(days=14))
def _initialize_formats(self) -> None:
"""Initialize all formatted date strings."""
try:
# Today's formats
self.today_Ymd_short = self.today.strftime("%Y%m%d")
self.today_Ymd_long = self.today.strftime("%Y-%m-%d")
self.today_jmA = self.today.strftime('%d/%m/%Y')
# Previous day formats
self.prev_day_Ymd_short = self.prev_day
self.prev_day_Ymd_long = self.prev_day.strftime('%Y-%m-%d')
# File names and display formats
self.prev_file_date = f"{self.prev_day_Ymd_short.strftime('%Y%m%d')}_{self.execution_hour}h"
self.file_date = f'{self.today_Ymd_short}_{self.execution_hour}h'
# Print formats
self.print_today = (f"{self.today.strftime('%d')} "
f"{self.MONTH_NAMES[self.today.strftime('%m')]} "
f"{self.today.strftime('%Y')}")
self.print_ppt_datetime = f"{self.today_jmA} ({self.execution_hour}h)"
self.print_xlsx_datetime = f"{self.print_today} ({self.execution_hour}h)"
self.print_prev_day = (f"{self.prev_day.strftime('%d')} "
f"{self.MONTH_NAMES[self.prev_day.strftime('%m')]} "
f"{self.prev_day.strftime('%Y')}")
# CSV file name
self.unite_csv = f"{self.file_date}_unite_latest.csv"
except Exception as e:
logger.error(f"Error initializing date formats: {str(e)}")
raise
def get_file_path(self, filename: str) -> Path:
"""Generate a Path object for a given filename."""
return Path(filename)
Functions
__post_init__()
Initialize calculated attributes after instance creation.
Source code in dashboard/src/date_manager.py
def __post_init__(self):
"""Initialize calculated attributes after instance creation."""
try:
self.execution_time = self._parse_datetime(self.execution_time)
self.execution_hour = self._calculate_execution_hour()
self._initialize_dates()
self._initialize_formats()
logger.info("DateTimeManager initialized successfully")
except Exception as e:
logger.error(f"Error during initialization: {str(e)}")
raise
get_file_path(filename)
Generate a Path object for a given filename.
Source code in dashboard/src/date_manager.py
def get_file_path(self, filename: str) -> Path:
"""Generate a Path object for a given filename."""
return Path(filename)
Functions
create_date_manager(dt_value=None)
Crée une instance de DateTimeManager avec gestion des erreurs.
| Parameters: |
|
|---|
| Returns: |
|
|---|
Source code in dashboard/src/date_manager.py
def create_date_manager(dt_value: Union[str, datetime, None] = None) -> DateTimeManager:
"""
Crée une instance de DateTimeManager avec gestion des erreurs.
Args:
dt_value: Valeur datetime optionnelle (utilise datetime.now() si None)
Returns:
Instance de DateTimeManager
"""
try:
execution_time = dt_value or datetime.now()
return DateTimeManager(execution_time)
except Exception as e:
logger.error(f"Erreur lors de la création du DateTimeManager: {str(e)}")
raise