def now(cls, tz: Optional[Union[str, Timezone]] = None) -> "DateTime": """ Get a DateTime instance for the current date and time. """ if has_test_now(): test_instance = get_test_now() _tz = pendulum._safe_timezone(tz) if tz is not None and _tz != test_instance.timezone: test_instance = test_instance.in_tz(_tz) return test_instance if tz is None or tz == "local": dt = datetime.datetime.now(local_timezone()) elif tz is UTC or tz == "UTC": dt = datetime.datetime.now(UTC) else: dt = datetime.datetime.now(UTC) tz = pendulum._safe_timezone(tz) dt = dt.astimezone(tz) return cls( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, tzinfo=dt.tzinfo, fold=dt.fold, )
def in_timezone(self, tz): # type: (Union[str, Timezone]) -> DateTime """ Set the instance's timezone from a string or object. """ tz = pendulum._safe_timezone(tz) return tz.convert(self, dst_rule=pendulum.POST_TRANSITION)
def in_timezone(self, tz: Union[str, Timezone]) -> "DateTime": """ Set the instance's timezone from a string or object. """ tz = pendulum._safe_timezone(tz) dt = self if not self.timezone: dt = dt.replace(fold=1) return tz.convert(dt)
def create( cls, year: int, month: int, day: int, hour: int = 0, minute: int = 0, second: int = 0, microsecond: int = 0, tz: Optional[Union[str, float, Timezone]] = UTC, fold: Optional[int] = 1, raise_on_unknown_times: bool = False, ) -> "DateTime": """ Creates a new DateTime instance from a specific date and time. """ if tz is not None: tz = pendulum._safe_timezone(tz) dt = datetime.datetime( year, month, day, hour, minute, second, microsecond, fold=fold ) if tz is not None: dt = tz.convert(dt, raise_on_unknown_times=raise_on_unknown_times) return cls( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, tzinfo=dt.tzinfo, fold=dt.fold, )
def test_safe_timezone_with_tzinfo_objects(): tz = _safe_timezone(pytz.timezone("Europe/Paris")) assert isinstance(tz, Timezone) assert "Europe/Paris" == tz.name