How to Use freezegun in Django Tests to Set the Date One Day Ahead with USE_TZ=True
Django
2019-03-25 23:57 (7 years ago)

reezegun is a Python library.
It hooks into the current time retrieval with datetime, allowing you to perform tests that assume "the next day" and similar scenarios.
If you want to perform tests in Django that assume "the next day":
今日のログインボーナス()
with freezegun.freeze_time(datetime.timedelta(days=1)):
明日のログインボーナス()
This might cause issues such as test failures before 9:00 AM when developing in the JST timezone.
from django.utils import timezone
今日のログインボーナス()
with freezegun.freeze_time(timezone.now() + datetime.timedelta(days=1)):
明日のログインボーナス()
The same goes for this case.
If you pass a timezone-aware datetime other than UTC to the freeze_time argument, the timezone may not be handled correctly in a development environment using the JST timezone.
To correctly determine the next day, you should do:
import datetime
今日のログインボーナス()
with freezegun.freeze_time(datetime.datetime.now() + datetime.timedelta(days=1)):
明日のログインボーナス()
or
import datetime
今日のログインボーナス()
with freezegun.freeze_time(datetime.timedelta(days=1), tz_offset=9):
明日のログインボーナス()
import datetime
from django.utils import timezone
tz = timezone.get_current_timezone()
今日のログインボーナス()
with freezegun.freeze_time(datetime.timedelta(days=1), tz_offset=tz._utcoffset):
明日のログインボーナス()
You need to set it up like this.
To generally freeze_time with an aware datetime
aware_datetime = ...
with freezegun.freeze_time(
aware_datetime, tz_offset=aware_datetime._utcoffset):
...
Please rate this article (No signup or login required)
Currently unrated
Related posts
How to Fix Display Issues in Django Admin Inlines After Upgrading to 5.1
Return Login and Redirect Views by Hardcoding Social Account Provider in django-allauth (When Using AWS Cognito, etc.)
After Upgrading to Django 5 and Updating Dependencies, SSL: CERTIFICATE_VERIFY_FAILED Error Occurs When Sending Emails
The "first" and "second" Arguments of assertEqual in Django's Unit Tests are Actually "expected" and "actual"
The author runs the application development company Cyberneura.
We look forward to discussing your development needs.
We look forward to discussing your development needs.