1

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?

5
  • 1
    Do the answers to this Q&A 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. Commented Aug 9, 2022 at 12:52
  • Yes, it is good idea, but how to convert it in Python? Commented Aug 9, 2022 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? Commented Aug 9, 2022 at 22:53
  • @AdrianKlaver, the type is DateTime, 2022-08-09 11:11:57.831000 +00:00 Commented Aug 10, 2022 at 7:50
  • 1
    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 <table_name>. Commented Aug 10, 2022 at 15:05

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.