Opened 8 years ago

Closed 8 years ago

Last modified 8 years ago

#27306 closed Cleanup/optimization (invalid)

Document relation between auto_now/auto_now_add and timezones

Reported by: Baptiste Mispelon Owned by: nobody
Component: Documentation Version: 1.10
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

The documentation for DateField.auto_now states: "Automatically set the field to now every time the object is saved." [1]

It achieves this by doing value = datetime.date.today(). However, as noted in the discussion on #27082 and #25181 this might not exactly be "now" (depending on what you think "now" means).

I think the documentation should clarify how auto_now interracts with timezone settings, and in particular what we mean when we say "now". I also think there's a bug lurking in the usage of datetime.date.today() and we should use the new timezone.localdate() instead.

[1] https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.DateField.auto_now

Change History (4)

comment:1 by Aymeric Augustin, 8 years ago

The current behavior is consistent with how Django handles time zones.

When the ORM must make a guess, it uses the default time zone, and that's what happens here.

comment:2 by Baptiste Mispelon, 8 years ago

Here's how our date/time-related fields handle auto_now*:

  • DateField uses datetime.date.today(): today's date in the default timezone
  • TimeField uses datetime.datetime.now().time(): the clock time in the default timezone
  • DateTimeField uses timezone.now(): the current datetime in the current timezone

("current" and "default" timezone are defined here: https://docs.djangoproject.com/en/1.10/topics/i18n/timezones/#default-time-zone-and-current-time-zone).

As Aymeric said, there's no bug here so this is only a documentation issue: we should clarify what "now" and "today" mean for auto_now.

comment:3 by Baptiste Mispelon, 8 years ago

Resolution: invalid
Status: newclosed

Turns out this is already documented in a "note" paragraph just under.

I should have read the documentation all the way through, sorry for the noise :(

comment:4 by Aymeric Augustin, 8 years ago

Small correction: timezone.now() is the current date and time in UTC, but that's irrelevant anyway: an aware datetime value will be stored correctly and can be converted in any timezone, so it doesn't matter what time zone the auto default value is generated in.

Note: See TracTickets for help on using tickets.
Back to Top