24👍
Prophylactics
You should avoid naive datetimes in the first place using the following:
from django.utils import timezone
now = timezone.now()
If like me, you have naive times already that you must convert, read on!
Django 4+:
Starting in Django 4, if you use zoneinfo
for timezone support (which is the default in Django 4) there’s nothing you need to do to use make_aware
to avoid this error. The is_dst
flag to make_aware is deprecated in Django 4 and will be removed in Django 5.
Django 1.9 – 3.2:
You can resolve the AmbiguousTimeError by using the following (thanks to GeyseR):
from django.utils import timezone
# This uses `settings.TIME_ZONE` unless you call `timezone.activate()`
timezone.make_aware(some_datetime, is_dst=False)
Django 1.x – 1.8:
The problem is that make_aware just calls timezone.localize, passing None to the argument is_dst:
timezone.localize(value, is_dst=None)
The argument is_dst is specifically what is used to resolve this ambiguous time error (http://pytz.sourceforge.net/#tzinfo-api).
The solution is to call timezone.localize yourself:
get_current_timezone().localize(some_datetime, is_dst=False)
Having is_dst=False sets it to the first of the two possible times. is_dst=True would be the second.
4👍
Since django 1.9 make_aware utility function has is_dst
parameter.
So you can use it for solving AmbiguousTimeError exception:
from django.utils.timezone import get_current_timezone, make_aware
make_aware(some_datetime, get_current_timezone(), is_dst=True)
or
make_aware(some_datetime, get_current_timezone(), is_dst=False)
- Django admin dropdown of 1000s of users
- Sometimes request.session.session_key is None
- Django. Error message for login form
3👍
For people searching on this error:
In your Django code, replace:
today = datetime.datetime.today()
with
from django.utils import timezone
today = timezone.now()
- Can Django run on Gunicorn alone (no Apache or nginx)?
- Django's {{ csrf_token }} is outputting the token value only, without the hidden input markup
- Clean Up HTML in Python
- Problem launching docker-compose : python modules not installed