import datetime as dt from dataclasses import dataclass import pytz from db.sf_connector import SnowflakeConnector __all__ = ["Timestamp", "TimestampError"] class TimestampError(Exception): pass @dataclass(frozen=True) class Timestamp: _value: dt.datetime @classmethod def from_sf(cls) -> "Timestamp": try: with SnowflakeConnector() as sf: sf_dt = sf.execute_query("SELECT CURRENT_TIMESTAMP(0) as TIMESTAMP;") except Exception as e: raise TimestampError("Something went wrong while acquiring timestamp") from e return cls(sf_dt[0]["TIMESTAMP"]) @classmethod def from_string(cls, timestamp: str) -> "Timestamp": try: datetime = dt.datetime.fromtimestamp(int(timestamp), tz=pytz.utc) except (ValueError, OSError) as e: raise TimestampError(f"'{timestamp}' is invalid timestamp") from e return cls(datetime) def __str__(self) -> str: return str(self.to_int()) def to_int(self) -> int: return int(self._value.timestamp()) def to_datetime(self) -> dt.datetime: return self._value def to_date(self): return self._value.date()