Search code examples
python-3.xdatetimetimedeltapytz

Find timezone time difference using pytz


I am creating a naive datetime object which contains no timezone information, but I know that it is always in UTC. I want to calculate the time difference between local time and UTC for any timezone I define, which would take into account DST as well.

What I am thus doing is the following:

from datetime import datetime, timedelta

now = datetime(2018,3,27,15,20)           #Create a naive datetime object
now_utc = timezone("UTC").localize(now)   # Add UTC timezone information to it
now_madrid = now_utc.astimezone(timezone("Europe/Madrid")) # convert to Madrid timezone

Normally, if I was to calculate the time difference between two datetime objects I would subtract them. But when I try diff = now_utc - now_madrid , the result is the following:

In [275]: now_utc-now_madrid
Out[275]: datetime.timedelta(0)

Can anyone please tell me, how I could find the timezone difference in this case? Thank you in advance :)


Solution

  • Time delta is "0" because Madrid is 2 hours head of UTC.

    now_utc-now_madrid
    

    When you subtract it like this means it's in another timezone behind UTC.

    There maybe a more efficient methods out there but this is how I would do it.

    >>> import pytz
    >>> import datetime
    >>> utc_now = pytz.utc.localize(datetime.datetime.utcnow ())
    >>> utc_now
    datetime.datetime(2018, 3, 27, 19, 11, 19, 659257, tzinfo=<UTC>)
    
    >>> madrid_now = utc_now.astimezone(pytz.timezone ('Europe/Madrid'))
    >>> madrid_now
    datetime.datetime(2018, 3, 27, 21, 11, 19, 659257, tzinfo=<DstTzInfo 'Europe/Madrid' CEST+2:00:00 DST>)
    

    As you can see, the timezone conversion is already provided by tzinfo CEST+2:00:00 DST.

    If you need to do any arithmetic on that value then try:

    >>> utc_now + timedelta (hours = 2)  # Since Madrid is +2:00:00 hours
    datetime.datetime(2018, 3, 27, 21, 11, 19, 659257, tzinfo=<UTC>)
    

    Or extract the offset timezone differences from strftime.

    >>> madrid_now.strftime ('%z')
    '+0200'
    

    You can find more reading here: http://pytz.sourceforge.net/