Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

1.1K
Visualizações
When to use datetime.utcnow() or datetime.now(tz=pytz.utc).replace(tzinfo=None)

I would like to understand when I should be using

datetime.now(tz=pytz.utc).replace(tzinfo=None)

as opposed to simply

datetime.utcnow()

Will the latter not take into account e.g. daylight savings?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

A lot of how datetime.datetime will work depends on the machine it is run on. The local time and time zone settings of the host machine will determine the output you will get.

If the host machine is in the UTC timezone then there will be no difference between datetime.datetime.now() and datetime.datetime.utcnow().

According to the pytz documentation:

The preferred way of dealing with times is to always work in UTC, converting to localtime only when generating output to be read by humans.

pytz is used for accounting for daylight savings time, and datetime.datetime.utcnow() is used to provide a universal standardised reference point upon which you can calculate daylight savings. datetime.datetime.utcnow() on it's own will not account for daylight savings.

over 4 years ago · Santiago Trujillo Relatório

0

You should never use datetime.utcnow() as it gives you a naïve timestamp that you can shoot yourself in the foot with. If you really want a naïve timestamp, make it explicit using your first option. now() takes the tz parameter (which you should always supply, to avoid using the host TZ). But utcnow() obviously doesn't provide that. So it is doomed.

For example, let's say you have a UTC timestamp, and you want to convert it to the local time in Mexico City:

my_timestamp.astimezone(pytz.timezone("America/Mexico_City"))

Looks fine, right? Nope, check this out:

>>> datetime.utcnow()
datetime.datetime(2021, 3, 29, 21, 40, 44, 329559)
>>> datetime.utcnow().astimezone(pytz.timezone("America/Mexico_City"))
datetime.datetime(2021, 3, 29, 21, 40, 44, 329559, tzinfo=<DstTzInfo 'America/Mexico_City' CST-1 day, 18:00:00 STD>)

As you can see, astimezone will just tack on the tz if you give it a naïve timestamp, without adjusting the actual time as expected. (if you didn't want to adjust, you'd have used .replace)

It's super confusing, and you don't run into problems like this if you just make sure you have no naïve timestamps. You can have them in your external APIs, if you like, but tack on a timezone when they enter the system.

To summarize: always use datetime.now(tz=some_tz).

over 4 years ago · Santiago Trujillo Relatório

0

To quote Paul Ganssle's article Stop using utcnow and utcfromtimestamp

[Don't] use utcnow() or utcfromtimestamp() simply because it's the wrong abstraction.

[...]

The reason that we cannot simply change utcnow() into an alias for now(timezone.utc) in the standard library is that would change the semantics of how those datetimes are treated by their consumers

IIRC, he contributed quite a bit to cpython (the core of Python) around datetime.

Hence: Don't use datetime.utcnow()

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda