0

Okay. I've read a bunch of other answers, but none of them seem to be doing what I need to do. I need some help with times and dates.

So I have an app such that the dates and times need to be based on the user's local time, but not change when the user changes time zones.

For example, say a user is in New York. The app needs to show the local time in New York. Then the user can save a particular date and time that they want to timestamp. All in New York time. To be more specific, they load the page at it shows 10:32 am which is the local time in New York, then they can log dates and times, say 1 pm local time in New York on Sept 3 (a week from the day they are logging).

But then that same user goes to Korea and they load the page. It now shows the local time in Korea, but the logged time now shows as Sept 3rd at 1 pm Korea time (not the equivalent of 1 pm in NY).

So I need to show local time based on the current timezone, but the logged datetimes are those datetimes are timezone naive.

I currently have timezone support turned off, but I can't get it to show local time in the app. I'm using timezone.now() to try to get the local time.

What is the best way to accomplish what I described above WITHOUT having the user specify their timezone manually every time they move around? Is this doable?

lovefaithswing
  • 1,510
  • 1
  • 21
  • 37
  • Can you save the time as a UTC, and then ALSO save the timezone that you want in a separate field? Then, at rendering time, you would convert your UTC date into the timezone saved in the separate timezone column. – Devon Aug 09 '22 at 02:04

1 Answers1

0

Always try to store the datetime objects as UTC. You have more reasons to do this since your app is operating on multiple timezones. This is also recommended by Django:

Even if your website is available in only one time zone, it’s still good practice to store data in UTC in your database.

  1. If a user saves a new record to the database, don't save the record as is, convert it first to UTC.

  2. Now, we have a fixed constraint that will make our lives easier, because when we retrieve a datetime value in the database, we know that it is in UTC, regardless if it was saved in New York on August 30, 13:00 GMT-4 or in Korea on August 31, 02:00 GMT+9, both will just be saved in the database as August 31, 17:00, UTC.

  3. Now, if a user loads the page, don't show the record as is, convert it first (which is now in UTC) to the current timezone of the user. This can be easily achieved through the datetime.astimezone() functionality.

  • I feel like you missed the point of the question. I don't want the timezone change. In your solution, if someone in NY saves a time as 4pm and then goes to Korea, that time will not longer show up as 4pm. But I WANT it to show up as 4pm, even in Korea. IE. I want users to see what time of day (wherever there were), they did something, not the equivalent of that in their new timezone. – lovefaithswing Sep 11 '21 at 03:09