Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django 1.4 timezone.now() vs datetime.datetime.now()

I'm a bit confused by the daylight savings handling

settings.py:

TIME_ZONE = 'Europe/London' USE_TZ = True 

in the django shell:

>>> from django.utils import timezone >>> import datetime >>> print timezone.now() 2012-05-28 11:19:42.897000+00:00 >>> print timezone.make_aware(datetime.datetime.now(),timezone.get_default_timez one()) 2012-05-28 12:20:03.224000+01:00 

why are they not the same with respect to daylight savings? Both should be locale aware, no?

I've read the docs but am none the wiser.

like image 315
meepmeep Avatar asked May 28 '12 11:05

meepmeep


People also ask

What timezone does datetime NOW () return?

The datetime. time class represents a notion of time as in hours, minutes, seconds and microseconds - anything that is less than a day. By default, the now() function returns time your local timezone.

How does Django use timezone now?

The solution to this problem is to use UTC in the code and use local time only when interacting with end users. Time zone support is disabled by default. To enable it, set USE_TZ = True in your settings file. In Django 5.0, time zone support will be enabled by default.

What is the default time zone setting in Django?

When USE_TZ is enabled, TIME_ZONE is the default time zone that Django will use to display datetimes in templates and to interpret datetimes entered in forms.

Does Python datetime include timezone?

One of the modules that helps you work with date and time in Python is datetime . With the datetime module, you can get the current date and time, or the current date and time in a particular time zone.


1 Answers

According to timezone.now() source:

def now():     """     Returns an aware or naive datetime.datetime, depending on settings.USE_TZ.     """     if settings.USE_TZ:         # timeit shows that datetime.now(tz=utc) is 24% slower         return datetime.utcnow().replace(tzinfo=utc)     else:         return datetime.now() 

It's based on utc instead of your default timezone. You could achieve same value by using

now = timezone.make_aware(datetime.datetime.now(),timezone.get_default_timezone()) print now.astimezone(timezone.utc) 
like image 53
okm Avatar answered Sep 23 '22 19:09

okm