Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

freezegun does not work with datetime.astimezone() #472

Open
lalten opened this issue Oct 19, 2022 · 0 comments
Open

freezegun does not work with datetime.astimezone() #472

lalten opened this issue Oct 19, 2022 · 0 comments

Comments

@lalten
Copy link

lalten commented Oct 19, 2022

freezegun does not work with datetime.astimezone()

ipython
Python 3.8.10 (default, Jun 22 2022, 20:18:18)
Type 'copyright', 'credits' or 'license' for more information
IPython 8.5.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: import datetime

In [2]: now = datetime.datetime.now(tz=datetime.timezone.utc)

In [3]: now.isoformat()
Out[3]: '2022-10-19T10:25:03.584218+00:00'

In [4]: now.astimezone().isoformat()
Out[4]: '2022-10-19T12:25:03.584218+02:00'

But

	import datetime
	
    @freeze_time("2000-01-01T00:00:00.000Z", tz_offset=3)
    def test_timezone() -> None:
        now = datetime.datetime.now(tz=datetime.timezone.utc)
        assert now.isoformat() == "2000-01-01T03:00:00+00:00"
>       assert now.astimezone().isoformat() == "2000-01-01T06:00:00+03:00"
E       AssertionError: assert '2000-01-01T03:00:00+00:00' == '2000-01-01T06:00:00+03:00'
E         - 2000-01-01T06:00:00+03:00
E         ?             ^        ^
E         + 2000-01-01T03:00:00+00:00
E         ?             ^        ^

Relevant datetime source is here:
https://github.com/python/cpython/blob/main/Lib/datetime.py#L1963-L1998

Problematic line in freezegun is here:

tz = tzlocal()

Workaround:

import datetime
import dateutil.tz
from unittest import mock

@mock.patch("freezegun.api.tzlocal", lambda: dateutil.tz.tzoffset("", datetime.timedelta(hours=3)))
@freeze_time("2000-01-01T00:00:00.000Z", tz_offset=3)
def test_timezone() -> None:
    now = datetime.datetime.now(tz=datetime.timezone.utc)
    assert now.isoformat() == "2000-01-01T03:00:00+00:00"
    assert now.astimezone().isoformat() == "2000-01-01T06:00:00+03:00"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant