[Answered ]-Why is timezone.now showing a future date when being applied as a default value to DateField in django

1πŸ‘

βœ…

I think the reason this happens is because the "date" (without the time) isn’t timezone aware.

You can see in the DateField source where Django automatically converts a datetime back to UTC:

    def _check_fix_default_value(self):
        """
        Warn that using an actual date or datetime value is probably wrong;
        it's only evaluated on server startup.
        """
        if not self.has_default():
            return []

        value = self.default
        if isinstance(value, datetime.datetime):
            value = _to_naive(value).date()  # <β€”β€”β€”β€”β€” HERE!
        elif isinstance(value, datetime.date):
            pass
        else:
            # No explicit date / datetime value -- no checks necessary
            return []
        # At this point, value is a date object.
        return self._check_if_value_fixed(value)

Personally I would use a DateTimeField so you keep the timezone information, and just access .date when you need it, but you should be able to use datetime.date.today (assuming you don’t want to use the auto_now_add option for some reason):

import datetime

class Submission(models.Model):
    date_created = models.DateField(
        default=datetime.date.today,
        blank=True,
    )
πŸ‘€davegaeddert

0πŸ‘

If you want the date_created field to store the correct date of creation, you can modify the default value with this: default=timezone.now().date()

The .date() method returns the date portion of a DateTime object and this will set the date_created field to "2023-03-01" (In your case – New DB Entry will require), which is the correct date of creation.

So you can try the code as per below:

class Submission(models.Model):
    date_created = models.DateField(
        default=timezone.now().date(),
        blank=True,
    )

    datetime_created = models.DateTimeField(
        default=timezone.now,
    )

The reason of the date_created field is set to "2023-03-02" is that the DateField type only stores the date, without the time information so when you set the default value to timezone.now it will take the time zone information specified in your settings.py file.
As you have set the time zone to "US/Mountain" on settings.py file, which is 7 hours behind UTC. Since the TIME_ZONE setting was set to "US/Mountain" when the data entry happens at 5 PM MST on 03/01/2023, the actual date in UTC was 02/01/2023 (time difference between MST and UTC). This is the reason why the value for date_created was set to "2023-03-02" for you.
You can check timezone converter

Leave a comment