spulec / freezegun

Let your Python tests travel through time
Apache License 2.0
4.2k stars 269 forks source link

Error using stdlib datetime when frozen to pendulum datetime instance. #411

Open alext opened 3 years ago

alext commented 3 years ago

I'm seeing the following error when using the stdlib datetime.now while time is frozen to a pendulum datetime object:

$ python
Python 3.8.10 (default, May 13 2021, 16:53:21) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime, timezone
>>> import pendulum
>>> from freezegun import freeze_time
>>> now = pendulum.now()
>>> now
DateTime(2021, 8, 23, 17, 7, 31, 402237, tzinfo=Timezone('Europe/London'))
>>> with freeze_time(now):
...     d = datetime.now(tz=timezone.utc)
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/home/alex/.pyenv/versions/3.8.10/lib/python3.8/site-packages/freezegun/api.py", line 386, in now
    result = tz.fromutc(now.replace(tzinfo=tz)) + cls._tz_offset()
ValueError: fromutc: dt.tzinfo is not self
>>>

freezegun: 1.1.0 pendulum: 2.1.2

Use-case for mixing the 2 datetime libraries is that my app code uses pendulum, but uses a library that uses the stdlib datetime libraries.

rodrigondec commented 3 years ago

Bump +1

hongquan commented 2 years ago

One workaround is to convert to ISO string before passing to freeze_time.

spra85 commented 2 months ago

If it helps anybody, we wrote a simple wrapper a while ago. Will also throw it out there to the maintainers of this repo that happy to submit a similar, simple fix, if amenable:

def freeze_time(when: str | date | datetime):
    """Drop-in replacement that fixes library error working with Pendulum datetime instances.

    https://github.com/spulec/freezegun/issues/411
    """
    return freezegun.freeze_time(when if isinstance(when, str) else when.isoformat())