Bart
Bart

Reputation: 552

Django DATETIME_FORMAT incorrect (by one year) for specific dates

For a client I am storing event logs in a postgres database. Each event has a date that is stored as a timestamp with time zone in postgres. The date is automatically populated using Djangos' built in auto_now_add attribute in the model definition.

In settings.py I have set the following:

TIME_ZONE = 'UTC'
USE_TZ = True
DATETIME_FORMAT = 'd/m/o H:i:s'
DATE_FORMAT = 'd/m/o'
TIME_FORMAT = 'H:i:s'
SHORT_DATE_FORMAT = 'd/m/o'
SHORT_DATETIME_FORMAT = 'd/m/o H:i'

I have lots of experience with this mechanism and it never caused problems until now. The client actually pointed out that there were a number of entries with a date lying in the future (impossible for event log).

After checking the front-end as well as the admin I can verify that there are invalid dates e.g.(30/12/2020 and 31/12/2020) appearing (all invalid dates are in this range, other dates before and after are displaying correctly). When I check the database (Postgres) I can verify that the dates stored are actually both in 2019 having the following timestamp values: 2019-12-30 10:23:07.451674+00 and 2019-12-31 08:12:26.635693+00.

The template in use in the frontend uses {{ log_item.date }} to display the date.

What am I missing? Any hints appreciated.

Upvotes: 1

Views: 314

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47354

Use DATE_FORMAT = 'd/m/Y' instead of DATE_FORMAT = 'd/m/o'. When you using o formating for year it's return week-numbering year. Since 30 and 31 december was in first week of 2020 year, it give you 2020.

Upvotes: 2

Related Questions