0

The server's timezone is +00:00, web site (running Flask, Heroku) users timezone is "Europe/Kiev" +03:00. I'm using this code to save a date and time to db:

created_at = db.Column(
    db.DateTime(timezone=True),
    nullable=False,
    server_default=db.func.now(),
)

But it saves it like 2022-08-09 11:11:57.831000 +00:00 and the time on fromtend shows the same way. How to save my local time to DB or how to show time considering my local timezone?

davidism
  • 121,510
  • 29
  • 395
  • 339
Vitalii Mytenko
  • 544
  • 5
  • 20
  • 1
    Do the answers to [this Q&A](https://stackoverflow.com/q/5876218/5320906) help you? Usually it's a good idea to store times as UTC and then let the front end convert to local time - see for example the answers to [this Q&A](https://stackoverflow.com/q/6525538/5320906). – snakecharmerb Aug 09 '22 at 12:52
  • Yes, it is good idea, but how to convert it in Python? – Vitalii Mytenko Aug 09 '22 at 14:55
  • 1) What is the actual type for the `created_at` field in the database? 2) Is the datetime/timestamp starting out as `2022-08-09 14:11:57.831`? – Adrian Klaver Aug 09 '22 at 22:53
  • @AdrianKlaver, the type is DateTime, `2022-08-09 11:11:57.831000 +00:00` – Vitalii Mytenko Aug 10 '22 at 07:50
  • No, `datetime` is a Python type. The type in the database field will either be `timestamp` or timestamptz`. You need to look at the schema definition for the database table. Using the Postgres command line client `psql` that can be done with `\d `. – Adrian Klaver Aug 10 '22 at 15:05

1 Answers1

1

As long as you're using a simple default (python datetime.datetime.now or SQL NOW), your application cannot be aware of the user's timezone.

There is two ways you can handle the user timezone, but for both the UTC datetime is stored in the database (I use python datetime.datetime.utcnow):

  • the "new method", on the client side the datetime is converted to local timezone using some javascript
  • the "classical method", on the server side, the timezone information is pulled from the user/browser (js or user enters it upon registering, etc) and conversions are done by the server using this information

Since you have not shown how the frontend looks, I can't recomment one specifically, but the "new method" is simplest in my mind.

ljmc
  • 4,830
  • 2
  • 7
  • 26