简体   繁体   中英

How do I get the correct difference between python daytime.time from different time zones?

I have instantiated two datetime.time objects with different time zones. Then I try to get the difference of time between both objects. In this example, I have set a time in La Paz and another in Lima (10:29 both in their respective timezones). Then I used datetime.combine to try to get the difference of time.

from datetime import time, datetime, date
from pytz import timezone

departure_timezone = timezone('America/La_Paz')
arrival_timezone = timezone('America/Lima')
departure_time = time(hour=10, minute=29, tzinfo=departure_timezone)
arrival_time = time(hour=10, minute=29, tzinfo=arrival_timezone)

dateTimeA = datetime.combine(date.today(), departure_time)
dateTimeB = datetime.combine(date.today(), arrival_time)

diff = dateTimeB - dateTimeA

print(dateTimeA)
print(dateTimeB)

print(diff)

Then it prints

2018-02-20 10:29:00-04:33
2018-02-20 10:29:00-05:08
0:35:00

which is not what I expected, since the time difference between La Paz and Lima is 1 hour, but instead I get 35 min. What do I need to change to get the expected outcome?

You need to use the timezone.localize() method; the pytz timezones contain all historical timezone changes, and assigning to tzinfo will always do the wrong thing. See the documenation :

This library only supports two ways of building a localized time. The first is to use the localize() method provided by the pytz library.

[...]

Unfortunately using the tzinfo argument of the standard datetime constructors ''does not work'' with pytz for many timezones.

 >>> datetime(2002, 10, 27, 12, 0, 0, tzinfo=amsterdam).strftime(fmt) '2002-10-27 12:00:00 LMT+0020' 

It is safe for timezones without daylight saving transitions though, such as UTC[.]

Neither method can be applied to a time() object; apply it to the datetime object instead:

dateTimeA = departure_time.tzinfo.localize(
    datetime.combine(date.today(), departure_time, tzinfo=None))
dateTimeB = arrival_time.tzinfo.localize(
    datetime.combine(date.today(), arrival_time, tzinfo=None))

The above re-uses the tzinfo reference on the departure_time time object and sets tzinfo to None , explicitly, to produce a correct timezone offset.

With those changes, the output becomes:

2018-02-20 10:29:00-04:00
2018-02-20 10:29:00-05:00
1:00:00

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM