Shouldn't django now () be in the default timezone?

This might be a bit of a trivial question, but I can't get django now () to be in the time zone defined in settings.TIME_ZONE ?

This is what actually happens:

 >>> from django.utils import timezone >>> timezone.now() datetime.datetime(2012, 5, 30, 16, 30, 0, 782087, tzinfo=<UTC>) >>> timezone.get_default_timezone() <DstTzInfo 'Asia/Singapore' SMT+6:55:00 STD> 
+6
source share
3 answers

Or I could just read the 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() 

The answer is no, I have to adjust it myself.

+1
source

Django source code (as shown in the selected answer) explains the concept of timezone.now() :

  • datetime.now() gives the current time (in your active time zone!) without time zone information ("naive datetime"), whereas ...
  • timezone.now() always gives the current time in UTC (!) format with information about the time zone.

This is annoying at first sight, yes. They might decide to devote the current time to the active time zone, but they did not. You can use timezone.localtime(timezone.now()) to get what you want:

 from django.utils import timezone from datetime import datetime timezone.get_current_timezone() # <DstTzInfo 'Antarctica/McMurdo' LMT+11:39:00 STD> datetime.now() # datetime.datetime(2014, 8, 19, 20, 8, 8, 440959) timezone.localtime(timezone.now()) # datetime.datetime(2014, 8, 19, 20, 8, 14, 889429, tzinfo=<DstTzInfo 'Antarctica/McMurdo' NZST+12:00:00 STD>) timezone.now() # datetime.datetime(2014, 8, 19, 8, 8, 22, 273529, tzinfo=<UTC>) datetime.utcnow() # datetime.datetime(2014, 8, 19, 8, 8, 29, 769312) 

For beginners and regular users, timezone.localtime(timezone.now()) is probably the most intuitive. Local time that still stores time zone information.

+9
source

It depends on the

now () Returns a knowing or naive datetime that represents the current point in time when USE_TZ is True or False, respectively.

https://docs.djangoproject.com/en/dev/ref/utils/#django-utils-timezone

Thus, everything will indicate that USE_TZ is false in your case, and this does not take TZ into account.

0
source

Source: https://habr.com/ru/post/917030/


All Articles