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

[#322] Fix seq for timezone-aware start value #353

Merged
merged 2 commits into from
Oct 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
### Added

### Changed
- Fixed a bug with `seq` being passed a tz-aware start value [PR #353](https://github.com/model-bakers/model_bakery/pull/353)

### Removed

Expand Down
3 changes: 2 additions & 1 deletion model_bakery/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,8 @@ def seq(value, increment_by=1, start=None, suffix=None):
date = value

# convert to epoch time
start = (date - datetime.datetime(1970, 1, 1)).total_seconds()
epoch_datetime = datetime.datetime(1970, 1, 1, tzinfo=date.tzinfo)
start = (date - epoch_datetime).total_seconds()
increment_by = increment_by.total_seconds()
for n in itertools.count(increment_by, increment_by):
series_date = tz_aware(datetime.datetime.utcfromtimestamp(start + n))
Expand Down
10 changes: 10 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ def test_datetime(self, settings, use_tz):
settings.USE_TZ = use_tz
tzinfo = datetime.timezone.utc if use_tz else None

# Starting with tz-unaware (naive) datetime
sequence = seq(
datetime.datetime(2021, 2, 11, 15, 39, 58, 457698),
increment_by=datetime.timedelta(hours=3),
Expand All @@ -160,6 +161,15 @@ def test_datetime(self, settings, use_tz):
2021, 2, 12, 00, 39, 58, 457698
).replace(tzinfo=tzinfo)

# Starting with tz-aware datetime
sequence = seq(
datetime.datetime(2021, 2, 11, 15, 39, 58, 457698, tzinfo=tzinfo),
increment_by=datetime.timedelta(hours=3),
)
assert next(sequence) == datetime.datetime(
2021, 2, 11, 18, 39, 58, 457698
).replace(tzinfo=tzinfo)

@pytest.mark.parametrize(
"value",
[
Expand Down