model-bakers/model_bakery

seq doesn't work for timezone aware datetime objects

knyghty opened this issue · 4 comments

Expected behavior

I expect to get a generator of datetimes.

Actual behavior

I got an exception.

Reproduction Steps

>>> from model_bakery.recipe import seq
>>> from datetime import datetime, timedelta, timezone
>>> dt = datetime(2022, 1, 1, tzinfo=timezone.utc)
>>> x = seq(dt, increment_by=timedelta(minutes=1))
>>> next(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/venv/lib/python3.10/site-packages/model_bakery/utils.py", line 85, in seq
    start = (date - datetime.datetime(1970, 1, 1)).total_seconds()
TypeError: can't subtract offset-naive and offset-aware datetimes

Versions

Python: 3.10
Django: 4.0.5
Model Bakery: 1.5.0

Hello @knyghty
Do you really need to make use of tzinfo=timezone.utc passing it as a parameter?
I ask this question because you can use the timezone set in the django settings see the example below:

>>> from model_bakery.recipe import seq
>>> from datetime import datetime, timedelta, timezone
>>> settings.configure(USE_TZ = True)
>>> dt = datetime(2022, 1, 1)
>>> x = seq(dt, increment_by=timedelta(minutes=5))
>>> next(x)
>>> datetime.datetime(2022, 1, 1, 0, 5, tzinfo=datetime.timezone.utc)

Other example this is https://github.com/model-bakers/model_bakery/blob/main/tests/test_utils.py#L146

@HigorMonteiro I suppose it's not necessary no, as long as everything comes out in UTC. However I do find this behaviour a bit odd and I would expect it to work with aware datetimes.

I actually find it a bit confusing that it silently converts naive datetimes into aware ones but chokes on already aware datetimes - I find it cleaner to deal with explicitly aware datetimes where possible.

I would tend to agree with @knyghty and it should be a relatively simple fix.

Hey @knyghty !

We released the fix for this issue in model-bakery 1.9.0.
Happy to get your feedback on how this works for you! 🙏