[Answered ]-How to make sure that the UTC date saved in the database is equivalent to midnight in the specified timezone in Django

1👍

Note: As in comments, this approach is not correct. We need to take date object in user’s timezone, as in the answer in duplicate question.

So, instead of date.today(), we would need: datetime.now(tz).date().


If I get your question right, you want to store midnight in suppose timezone +5:30, as 18:30 in UTC? If that is the case, you can do it like this:

>>> from datetime import date, time, datetime
>>> naive_midnight = datetime.combine(date.today(), time())
>>> tz = pytz.timezone('Asia/Kolkata')
>>>
>>> # Attach local timezone to above naive datetime object
>>> midnight_user_timezone = tz.localize(naive_midnight)
>>> print midnigth_user_timezone
2015-12-15 00:00:00+05:30
>>>
>>> # Convert to UTC
>>> midnight_to_utc = midnight_user_timezone.astimezone(pytz.UTC)
>>> print midnigth_to_utc
2015-12-14 18:30:00+00:00

1👍

Django has a function named make_aware to convert time zone naive datetime objects to time zone aware datetime objects.

aware_date_obj = make_aware(date_obj, user.timezone)

Since the datetime object is then already linked to the correct time zone, you can simply use your .replace(day=1, hour=0, minute=0, second=0, microsecond=0) on the aware_date_obj and you will get the beginning of the year at the specified time zone.

If the datetime object is already time zone aware but not in the correct time zone, you can use the astimezone to convert it to the correct timezone:

date_obj.astimezone(user.timezone)

Then you can again use the .replace function.

Finally, when Django stores the datetime object in the database, the time zone information will get lost. The time point will still be correct, but it will be linked to the default django time zone after the load from the database. You would then again have to use the astimezone function to link it to the correct time zone.

👤Tim

Leave a comment