Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

558
Vistas
Python Datetime : use strftime() with a timezone-aware date

Suppose I have date d like this :

>>> d 
datetime(2009, 4, 19, 21, 12, tzinfo=tzoffset(None, -7200))

As you can see, it is "timezone aware", there is an offset of 2 Hour, utctime is

>>> d.utctimetuple() 
time.struct_time(tm_year=2009, tm_mon=4, tm_mday=19, 
                 tm_hour=23, tm_min=12, tm_sec=0, 
                 tm_wday=6, tm_yday=109, tm_isdst=0)

So, real UTC date is 19th March 2009 23:12:00, right ?

Now I need to format my date in string, I use

>>> d.strftime('%Y-%m-%d %H:%M:%S.%f') 
'2009-04-19 21:12:00.000000'

Which doesn't seems to take this offset into account. How to fix that ?

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

In addition to what @Slam has already answered:

If you want to output the UTC time without any offset, you can do

from datetime import timezone, datetime, timedelta
d = datetime(2009, 4, 19, 21, 12, tzinfo=timezone(timedelta(hours=-2)))
d.astimezone(timezone.utc).strftime('%Y-%m-%d %H:%M:%S.%f')

See datetime.astimezone in the Python docs.

over 4 years ago · Santiago Trujillo Denunciar

0

The reason is python actually formatting your datetime object, not some "UTC at this point of time"

To show timezone in formatting, use %z or %Z.

Look for strf docs for details

over 4 years ago · Santiago Trujillo Denunciar

0

This will convert your local time to UTC and print it:

import datetime, pytz
from dateutil.tz.tz import tzoffset

loc = datetime.datetime(2009, 4, 19, 21, 12, tzinfo=tzoffset(None, -7200))

print(loc.astimezone(pytz.utc).strftime('%Y-%m-%d %H:%M:%S.%f') )

(http://pytz.sourceforge.net/)

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda