I found the following problem when creating an object of type datetime
with the constructor parameter tzinfo
that defines the time zone. To define a time zone I used the pytz
module as follows:
import pytz as tz
import datetime as dt
zona_horaria = tz.timezone("Europe/Madrid")
fecha1 = dt.datetime(2017, 8, 9, 10, 10, 10)
fecha2 = dt.datetime(2017, 8, 9, 10, 10, 10, tzinfo=zona_horaria)
fecha3 = dt.datetime(2017, 8, 9, 10, 10, 10).replace(tzinfo=zona_horaria)
fecha4 = dt.datetime(2017, 8, 9, 10, 10, 10, tzinfo=tz.UTC)
The evaluation of the variables fecha
give the following results:
fecha1
datetime.datetime(2017, 8, 9, 10, 10, 10)
fecha2
datetime.datetime(2017, 8, 9, 10, 10, 10, tzinfo=<DstTzInfo 'Europe/Madrid' LMT-1 day, 23:45:00 STD>)
fecha3
datetime.datetime(2017, 8, 9, 10, 10, 10, tzinfo=<DstTzInfo 'Europe/Madrid' LMT-1 day, 23:45:00 STD>)
fecha4
datetime.datetime(2017, 8, 9, 10, 10, 10, tzinfo=<UTC>)
If the variables are printed using str()
we get the following results:
str(fecha1)
'2017-08-09 10:10:10'
str(fecha2)
'2017-08-09 10:10:10-00:15'
str(fecha3)
'2017-08-09 10:10:10-00:15'
str(fecha4)
'2017-08-09 10:10:10+00:00'
As can be seen, the time offset of fecha2
and fecha3
is only -15 minutes compared to UTC, when it should be +2: 00 for the Madrid time. If it is checked with timestamp , the following results are obtained:
fecha1.timestamp()
1502266210.0
fecha2.timestamp()
1502274310.0
fecha3.timestamp()
1502274310.0
fecha4.timestamp()
1502273410.0
That is, the difference between fecha2
or fecha3
and fecha4
is 900 seconds (15 minutes), when it should be 2 hours. How can I create a datetime
start object by assigning it a time zone and that the correct phase shift is registered?
PD: If you create an object type datetime
using fromtimestamp()
it works, but you have to know before the timestamp UTC corresponding to the local date you want to create:
dt.datetime.fromtimestamp(timestamp, zona_horaria)