Rodrigo
Rodrigo

Reputation: 391

How to compare two timezone strings?

Is there some library or built-in to compare two timezones? What I want is the offset of hours between two timezones

For example:

hours = diff_timezones("America/Los_Angeles", "America/Sao_Paulo")

print(hours) # -> 3

Upvotes: 0

Views: 299

Answers (2)

urirot
urirot

Reputation: 399

This should work. and here's a great blog about timezones and datetime: Blog

import datetime, pytz


d_naive = datetime.datetime.now()

timezone_a = pytz.timezone("America/Los_Angeles")
timezone_b = pytz.timezone("America/New_York")

d_aware_a = timezone_a.localize(d_naive)
d_aware_b = timezone_b.localize(d_naive)

difference =  d_aware_a - d_aware_b

print(difference.total_seconds() / 60 / 60 ) # seconds / minutes

Upvotes: 1

Brad Solomon
Brad Solomon

Reputation: 40918

FYI: Python 3.9+ ships with zoneinfo in its standard library, while dateutil (below) is a third-party package available on PyPI as python-dateutil.


Using dateutil.tz.gettz:

from datetime import datetime, timedelta
from dateutil.tz import gettz

def diff_timezones(tz1: str, tz2: str) -> timedelta:
    zero = datetime.utcfromtimestamp(0)
    diff = zero.replace(tzinfo=gettz(tz1)) - zero.replace(tzinfo=gettz(tz2))
    return diff

Sample usage:

>>> diff_timezones('America/Los_Angeles', 'America/Sao_Paulo')
datetime.timedelta(seconds=18000)

The result here is a datetime.timedelta instance. To get a float of hours:

>>> td.total_seconds() / (60 * 60)
5.0

CAUTION: I don't believe this would take into account DST since it uses a fixed datetime of the Unix epoch (1970-01-01), so it might be off in cases where one area obeys DST and another does not. To account for that you might be able to use the current timestamp as a reference date instead.

Upvotes: 2

Related Questions