Comments (8)
Looks like freezegun has an incomplete implementation of datetime.now. It needs to support the tz argument for that to work.
I've had another problem with Django as well. In django.db.models.fields both DateField, DateTimeField have to_python methods that check is the value passed isinstance of datetime.datetime or datetime.date
For some reason real datetimes can get passed to it and this causes isinstance() to return False causing a failure. Maybe it's not clear where freezegun should be imported to avoid that but for now I have monkeypatched the to_python to check for both freezegun and real datetime objects.
from freezegun.
@hexsprite Is your monkey-patch workaround available somewhere? I'm also running into a problem on Django because the to_python method fails:
File "/Users/lorin/.virtualenvs/myvenv/src/django/django/db/models/query.py", line 1593, in insert_query
return query.get_compiler(using=using).execute_sql(return_id)
File "/Users/lorin/.virtualenvs/myvenv/src/django/django/db/models/sql/compiler.py", line 909, in execute_sql
for sql, params in self.as_sql():
File "/Users/lorin/.virtualenvs/myvenv/src/django/django/db/models/sql/compiler.py", line 872, in as_sql
for obj in self.query.objs
File "/Users/lorin/.virtualenvs/myvenv/src/django/django/db/models/fields/__init__.py", line 292, in get_db_prep_save
prepared=False)
File "/Users/lorin/.virtualenvs/myvenv/src/django/django/db/models/fields/__init__.py", line 717, in get_db_prep_value
value = self.get_prep_value(value)
File "/Users/lorin/.virtualenvs/myvenv/src/django/django/db/models/fields/__init__.py", line 712, in get_prep_value
return self.to_python(value)
File "/Users/lorin/.virtualenvs/myvenv/src/django/django/db/models/fields/__init__.py", line 684, in to_python
raise exceptions.ValidationError(msg)
django.core.exceptions.ValidationError: [u"'2013-01-24 21:31:16.235381' value has an invalid date format. It must be in YYYY-MM-DD format."]
from freezegun.
@lorin it ain't pretty but it works for me...
not sure if there's a more elegant way of getting around an isinstance() check in the original code...
import datetime
import freezegun
import logging
import warnings
from django.conf import settings
from django.db.models.fields import DateField, DateTimeField
from django.utils import timezone
log = logging.getLogger(__name__)
def monkeypatch_fields_for_freezegun():
_original_datefield_to_python = DateField.to_python
_original_datetimefield_to_python = DateTimeField.to_python
log.warn("monkey patching Django Date fields for freezegun support")
def _datefield_to_python(self, value):
if isinstance(value, freezegun.api.real_datetime):
if settings.USE_TZ and timezone.is_aware(value):
# Convert aware datetimes to the default time zone
# before casting them to dates (#17742).
default_timezone = timezone.get_default_timezone()
value = timezone.make_naive(value, default_timezone)
return value.date()
if isinstance(value, freezegun.api.real_date):
return value
return _original_datefield_to_python(self, value)
def _datetimefield_to_python(self, value):
if isinstance(value, freezegun.api.real_datetime):
return value
if isinstance(value, freezegun.api.real_date):
value = datetime.datetime(value.year, value.month, value.day)
if settings.USE_TZ:
# For backwards compatibility, interpret naive datetimes in
# local time. This won't work during DST change, but we can't
# do much about it, so we let the exceptions percolate up the
# call stack.
warnings.warn("DateTimeField received a naive datetime (%s)"
" while time zone support is active." % value,
RuntimeWarning)
default_timezone = timezone.get_default_timezone()
value = timezone.make_aware(value, default_timezone)
return value
return _original_datetimefield_to_python(self, value)
DateField.to_python = _datefield_to_python
DateTimeField.to_python = _datetimefield_to_python
monkeypatch_fields_for_freezegun()
from freezegun.
now() not accepting timezones is definitely a bug and should be fixed.
I'm not able to recreate the django saving bug though. isinstance() checks should all pass for the current version of freezegun.
from freezegun.
if I get a moment I'll try to create a minimal test case that demonstrates the isinstance() issue
from freezegun.
That would be great. Thanks.
from freezegun.
I think that a lot of these issues should be fixed in the newest release. Freezegun now only mocks datetime/date when activated. I haven't actually tested with django yet though.
from freezegun.
I think this should all be fixed with the latest release.
from freezegun.
Related Issues (20)
- 1 min difference when using `auto_tick_seconds`
- Doesnt change the time for subprocess HOT 2
- datetime.utcnow() and datetime.now() return same value HOT 1
- Drop usage of utcfromtimestamp HOT 1
- utcnow is deprecated HOT 1
- Add parameter to increase speed of time when tick=True
- `time_to_freeze.today()` returns wrong time and type if TZ is not 'UTC' in env vars HOT 2
- 'FakeDatetime' object cannot be interpreted as an integer
- Timezone America/Sao_Paulo triggers recursion errors in tests. HOT 3
- Maintenance plans HOT 3
- 1.3.0: `freezegun/__init__.py` is missing new version number HOT 1
- [Discussion] about freezing asyncio HOT 7
- ``PermissionError: [Errno 1] Operation not permitted`` appears when upgrading to ``1.3.0`` HOT 7
- Freezegun doesn't mock pointers to date functions HOT 1
- Tag for 1.2.2 is missing HOT 1
- Python 3.12: Deprecation warnings related to datetime.datetime.utcfromtimestamp HOT 2
- Time is not freezed when using `uvloop` event loop
- unsupported operand type(s) for +: 'FakeDatetime' and 'FakeDatetime'
- Datetime and Time packages do not have the same behavior when being frozen HOT 4
- timezone free datetime.datetime.fromtimestamp returns original datetime.datetime HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from freezegun.