pendulum icon indicating copy to clipboard operation
pendulum copied to clipboard

tz not taken into account when calling pendulum.instance

Open RobbertDM opened this issue 1 year ago • 4 comments

  • [x] I am on the latest Pendulum version.
  • [x] I have searched the issues of this repo and believe that this is not a duplicate.
  • OS version and name: ubuntu 22.04
  • Pendulum version: 3.0.0

Issue

If you pass a DateTime that has timezone information, for example pendulum.now(), to pendulum.instance(), the tz= argument seems to do nothing.

Try for example the following: pendulum.instance(pendulum.now(), tz="EST") For me, that returns DateTime(2024, 9, 3, 13, 56, 35, 64854, tzinfo=Timezone('Europe/Brussels')) since I am in Brussels.

I would expect this tz= argument for instance to make sure the returned object is in that timezone. If not, what is it used for?

RobbertDM avatar Sep 03 '24 12:09 RobbertDM

I think what you need is

pendulum.now().in_timezone('Europe/Brussels')

or even if actually using #now you can do directly

pendulum.now(tz='Europe/Brussels')

The instance method is I believe more intended for datetime.datetime conversion (into pendulum.Datetime).

stripedpumpkin avatar Oct 08 '24 11:10 stripedpumpkin

Yeah we already have our fix, I just wanted to report this behavior by the instance method, because I don't understand why there is a tz argument if it's not used? This caused a bug earlier in our code because we thought the pendulum.Datetime object that would come out of pendulum.instance(dt, tz='EST') would've been one with tzinfo=Timezone('EST') but it's not.

RobbertDM avatar Oct 08 '24 11:10 RobbertDM

My best guess is that pendulum.instance expects a datetime.datetime with a tzinfo attributes, not a pendulum.Datetime, as the point of #instance is to get a pendulum.Datetime, from a datetime.datetime I think.

stripedpumpkin avatar Oct 08 '24 12:10 stripedpumpkin

Ah ok here is what happens:

    @classmethod
    def instance(
        cls,
        dt: datetime.datetime,
        tz: str | Timezone | FixedTimezone | datetime.tzinfo | None = UTC,
    ) -> Self:
        tz = dt.tzinfo or tz

        if tz is not None:
            tz = pendulum._safe_timezone(tz, dt=dt)

If you pass a pendulum DateTime as argument it will have a tzinfo, so this will take priority over the one you injected. But again I don't think this method is intended to perform time zone conversions as discussed above.

stripedpumpkin avatar Oct 08 '24 12:10 stripedpumpkin