Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolving AmbiguousTimeError from Django's make_aware

I have a code as follows:

from django.utils.timezone import get_current_timezone, make_aware

make_aware(some_datetime, get_current_timezone())

The make_aware call occasionally raises

AmbiguousTimeError: 2013-11-03 01:23:17

I know from the Django docs that this is a daylight savings problem, and that this timestamp is in fact ambiguous. Now how do i resolve it (say to the first of the two possible times this could be)?

like image 834
Zags Avatar asked Jan 30 '14 19:01

Zags


3 Answers

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 1.9+:

You can resolve the AmbiguousTimeError by using the following (thanks to GeyseR):

make_aware(some_datetime, get_current_timezone(), 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.

like image 87
Zags Avatar answered Sep 18 '22 21:09

Zags


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)

Related section in django docs

like image 20
GeyseR Avatar answered Sep 16 '22 21:09

GeyseR


For people searching on this error:

In your Django code, replace:

    today = datetime.datetime.today()

with

    from django.utils import timezone

    today = timezone.now()
like image 24
Michael van de Waeter Avatar answered Sep 18 '22 21:09

Michael van de Waeter