Change time to UTC

0

I have a doubt I think simple: I have a time read in a file and want to change it to UTC format.

For example:

#esto es lo que tengo importado:
import datetime ,time
from pytz import timezone 

def cambio_fecha_hora_utc():
    fecha = 20180613
    hora = 17
    fecha_hora = fecha + hora

    tz = timezone("Europe/Madrid")  # obtengo la hora de Madrid que es donde estoy
    #lo que me gustaría es que me devolviera 
    fecha_hora_utc = #la fecha y la hora  ya en el formato utc

Greetings and grace

    
asked by Tercuato 13.06.2018 в 17:41
source

1 answer

2

Convert your string to datetime first to be able to apply the localize method to add information of the time zone. Done this you only need to use the astimezone method to perform the conversion to any supported time zone:

import datetime
import pytz



def cambio_fecha_hora_utc(fecha):
    timezone = pytz.timezone("Europe/Madrid")
    fecha_local = timezone.localize(fecha, is_dst=None)
    fecha_utc = fecha_local.astimezone(pytz.utc)
    return fecha_utc


# Ejemplo
fecha = "20180613"
hora = "17"
dt = datetime.datetime.strptime(fecha + hora, "%Y%m%d%H")
df_utc = cambio_fecha_hora_utc(dt)
print df_utc
#2018-06-13 15:00:00+00:00

The output is a datetime.datetime object:

>>> dt_utc
datetime.datetime(2018, 6, 13, 15, 0, tzinfo=<UTC>)
    
answered by 13.06.2018 в 18:01