How to set only for a column the datetime type without time zone on postgres?

I’m using the timezone “America/São paulo” -3 in mya db postgres and for only a column in my table “X” I need to use a column datetime without any timezone.

What can I do in this situation?

Olá, parece que você é do Brasil também!
Normalmente acabamos criando mais problemas de fuso horário quando removemos o fuso horário de um objeto datetime. Qual o objetivo da coluna não ter fuso horário?

Hey there, it looks like you’re from Brazil too!
Normally we end up creating more timezone problems when we remove the timezone from a datetime object. What’s the objective of this column having no timezone?

Olá, bom dia! Isso mesmo, sou do Brasil também.

Primeiro de tudo eu preciso entender qual seria o padrão a ser usado no banco de dados. Caso tenha conhecimento sobre, seria melhor armazenar um timestamp considerando fuso horário ou não?

Segundo, não tenho muito dominio nessa questão de timestamp então, minha necessidade nesse momento é procurar entender qual o melhor caminho para armazenar timestamp sem ter problemas de fuso horário.

No meu caso, eu preciso guardar as informações de transações financeiras. Sendo assim, se uma transação ocorreu às 12:00:54 independentemente de quem consumir essa informação ou até mesmo se eu migrar para outro banco de dados que esteja trabalhando com um fuso diferente, eu quero que essa informação sempre seja 12:00:54.

Imagine que eu possua um app bancário e na tela de extrato eu consulte todas as minhas movimentações, se o meu app estiver aplicando um fuso -3, essa transação iria ser apresentada como 9:00:54, que não faz sentido. O mesmo vale se o fuso usado fosse +3, então seria apresentado 15:00:54.

O que quero é, apresentar sempre a hora certa, 12:00:54.

Diante deste cenário, qual seria o melhor caminho?

Good morning! That’s right, I’m from Brazil too.

First of all I need to understand what would be the pattern to use in the database. If you know about it, would it be better to store a timestamp considering timezone or not?

Second, I don’t know much about timestamps, so my need at the moment is to try to understand the best way to store timestamps without having time zone problems.

In my case, I need to save financial transaction information. Therefore, if a transaction occurred at 12:00:54 regardless of who consumes this information or even if I migrate to another database that is working with a different time zone, I want this information to always be 12:00:54 .

Imagine that I had a banking app and on the statement screen I consulted all my transactions, if my app were applying a -3 time zone, this transaction would be presented as 9:00:54, which makes no sense. The same goes for if the time zone used was +3, then 15:00:54 would be displayed.

What I want is to always show the right time, 12:00:54.

Given this scenario, what would be the best way?

Agora ficou claro o que você quis dizer! Peço que por gentileza edite sua resposta para incluir um texto em inglês também, já que esse fórum tem o idioma principal em inglês e isso pode ajudar outras pessoas a encontrar a resposta para a mesma pergunta, você pode usar o google tradutor para não ter que digitar tudo novamente.

Mas vamos às suas perguntas:

Com certeza armazenar com fuso horário.

Não posso dizer que eu concordo com essa informação da “hora certa”. A “hora certa” é relativa para cada fuso horário. Por exemplo, se eu estou no Brasil e fiz a transação dia 23 de Fevereiro de 2023 às 09:00:54, eu acharia muito estranho ver no meu extrato que a transação está registrada às 12:00:54. O que deve acontecer nesse cenário é o seguinte:
O horário é salvo no banco de dados em UTC preferencialmente.
Quando o valor é exibido para o usuário é informado no seu fuso horário.

Eu gosto bastante deste vídeo, que explica um pouco deste conceito.

There follows the above response on english, directly from translate:

Now it’s clear what you mean! I ask you to kindly edit your answer to include a text in English as well, as this forum has the main language in English and this can help other people to find the answer to the same question, you can use google translate so you don’t have to type everything again.

But on to your questions:

Definitely store with time zone.

I can’t say that I agree with this “right time” information. The “right time” is relative to each time zone. For example, if I am in Brazil and I made the transaction on February 23, 2023 at 09:00:54, I would find it very strange to see on my statement that the transaction is recorded at 12:00:54. What should happen in this scenario is the following:
The time is saved in the database in UTC preferably.
When the value is displayed to the user, it is informed in their time zone.

I really like this video, which explains a little of this concept.

I forgot to mention, the documentation on timezone explains this concept as well.

Vamos ver se entendi direito, se meu banco de dados estivesse configurado para utilizar o UTC, isso significa que uma transação realizada no brasil às 9:00:54 seria gravada no banco como 12:00:54.

Sendo assim, caso eu consulte meu extrato no brasil e meu app estive pegando o timezone local como GMT-3 então ele seria apresentado como 9:00:54.

Agora, se eu estive consultando fora do país e meu app estive pegando um timezone GMT +4 ele seria apresentado como 16:00:54. Correto? Se sim, isso não seria errado?

Se não seria dessa forma, qual horário que deveria ser apresentado?

Vou incrementar um pouco mais esse exemplo…suponha que eu aqui no brasil esteja cadastrando um agendamento de transferência para 09:00:54 e meu gerente que reside na ásia resolve visualizar meu agendamento para que ele saiba que horas precisa fazer a transferência para minha conta. Qual seria o horário que ele deveria estar visualizando?

Let’s see if I understood correctly, if my database was configured to use UTC, that means that a transaction performed in Brazil at 9:00:54 would be recorded in the database as 12:00:54.

So, if I check my statement in Brazil and my app is getting the local timezone as GMT-3 then it would be presented as 9:00:54.

Now, if I was querying outside the country and my app was getting a GMT +4 timezone it would be displayed as 16:00:54. Correct? If so, wouldn’t that be wrong?

If not, what time should it be presented?

I’m going to increase this example a little more…suppose that here in Brazil I am registering a transfer schedule for 09:00:54 and my manager who lives in Asia decides to view my schedule so that he knows what time he needs to make the transfer transfer to my account. What time should he be viewing?

Se você estivesse fora do país, a hora em que você estivesse consultando seria maior que 16:00:54 por que você também estaria nesse fuso horário, então mesmo que quando no Brasil sua transação foi efetuada as 09:00:54, no local que você está agora eram 16:00:54 o que significa que está correto. Por isso você salva a informação no banco em UTC, e apresenta a data no fuso horário da pessoa.

Ele vai estar visualizando no fuso horário local dele, que pode ser por exemplo +01:00, o que corresponde ao horário de 13:00:54, se ele fizer a sua transferência nesse horário, será o horário que você agendou. Não importa onde a pessoa esteja, o “horário será o mesmo” relativamente.


If you were outside the country, the time you were querying would be greater than 16:00:54 because you would also be in that time zone, so even if when in Brazil your transaction was carried out at 09:00:54, in the local that you are now was 16:00:54 which means that is correct. That’s why you save the information in the database in UTC, and present the date in the person’s time zone.

He will be viewing in his local time zone, which can be for example +01:00, which corresponds to the time of 13:00:54, if he transfers at that time, it will be the time you scheduled. No matter where the person is, the “time will be the same” relatively.

1 Like

Perfeito consegui comprender.

Agora, estou recebendo um json com uma tag contendo a data e hora da transação no formato UTC ( ISO-8601), conforme abaixo:

Operação realizada às 9:16:00 e no json veio como “2023-02-21T12:16:00+00:00”.

Primeiramente, meu banco (postgres) está configurado para utilizar o UTC-3 e meu projeto também.

Minha api simplesmente recebe essa dado, cria um objeto com base em uma model ao qual possui um campo DateTimeField e nele é gravado essa informação ao qual, quando dou um save acaba gravando “9:16:00” no banco de dados.

Seguindo a ideia de que desejo agora grava-lo em UTC, como eu faço para receber essa data do json passar para o meu objeto e grava-lo no banco como “2023-02-21T12:16:00+00:00”?

Perfect, I understand.

Now, I’m getting a json with a tag containing the transaction date and time in UTC format, as below:

Operation performed at 9:16:00 and the json came as “2023-02-21T12:16:00+00:00”.

First, my database (postgres) is configured to use UTC-3 and so is my project.

My api simply receives this data, creates an object based on a model which has a DateTimeField field and this information is recorded in it, which, when I give a save, ends up recording “9:16:00” in the database.

Following the idea that I now want to record it in UTC, how do I receive this json data, pass it to my object and record it in the database as “2023-02-21T12:16:00+00:00”?

É bem provável que no seu banco de dados esteja salvo com a flag do timezone também.
Algo assim: “2023-02-21T09:16:00-03:00”
Se esse for o caso, você já está “seguro” com o fuso horário, já que tendo a informação do fuso horário é fácil convertê-lo para outro fuso horário.

It is very likely that your database is saved with the timezone flag as well.
Something like this: “2023-02-21T09:16:00-03:00”
If that’s the case, you’re already “secure” with the time zone, as having the time zone information it’s easy to convert it to another time zone.

Correto. No banco já está sendo gravado dessa forma e com isso, será mais fácil gerencia-lo, principalmente na conversão para outros fusos.

Agradeço pela sua disponibilidade e ajuda.

Sucesso!

Correct. The database is already being recorded this way and with that, it will be easier to manage it, especially when converting to other zones.

Thank you for your availability and help.

Success!

1 Like