I have a database model that includes a DateTimeField
as below:
class Person(models.Model):
....
date_of_birth = models.DateTimeField()
date_of_birth_precision = models.CharField(max_length=3, choices=(
('D', 'Day'),
('H', 'Hour'),
('Min', 'Minute'),
('S', 'Second')
))
I have USE_TZ = True
in my settings.py
.
My indentation is to give the user the flexibility to input the date_of_birth
with the precision he wants according to the selected date_of_birth_precision
, and I have already handled the picker format according to the selected date_of_birth_precision
. So, for an instance, the input could be 1992-07-28
, 1992-07-28 15
, 1992-07-28 15:33
, or 1992-07-28 15:33:45
depending on the selected precision.
To be able to accept those different formats in my form, I have extended the accepted formats in settings.py
as below:
DATETIME_INPUT_FORMATS += (
"%Y-%m-%d %H",
)
Timezone Problem Statement:
So far, everything is working fine only if I have time fractions.
Suppose that the input date is 1992-07-28
with precision Day
and my local time zone is UTC+2
, the value will be converted to UTC to be 1992-07-27 22:00:00
in database.
Now, when a user, for an instance, with time zone UTC+1
reads the date_of_birth
, it will be translated initially from the database to 1992-07-27 23:00:00
, then I will parse it to the user with Day
precision to be 1992-07-27
which is not correct in my business case.
In my business case, I want the date_of_birth
to be time-zone-aware only if there are time fractions, and to be saved naïve as it is and to be translated to the user as it is if there is no time fraction. How can I achieve that?