Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get hours difference from UTC to given timezone?

Tags:

python

Is there a way to get how many hours a differene there is between UTC and a given timezone?

For instance the difference between UTC and Europe/Amsterdam is +2 hours.

Is there something in python for this?

like image 587
w00 Avatar asked Jul 04 '12 13:07

w00


1 Answers

Let's say you have a datetime with timezone:

import datetime
import pytz

d = datetime.datetime(2012, 1, 1, 0, 0, 0, tzinfo=pytz.utc)
In [54]: d
Out[54]: datetime.datetime(2012, 1, 1, 0, 0, tzinfo=<UTC>)

to convert this to Amsterdam time, use:

ams = pytz.timezone('Europe/Amsterdam')

In [55]: d.astimezone(ams)
Out[55]: datetime.datetime(2012, 1, 1, 1, 0, tzinfo=<DstTzInfo 'Europe/Amsterdam' CET+1:00:00 STD>)

pst = timezone('US/Pacific')
In [118]: d.astimezone(pst)
Out[118]: datetime.datetime(2011, 12, 31, 16, 0, tzinfo=<DstTzInfo 'US/Pacific' PST-1 day, 16:00:00 STD>)

If we have a datetime without timezone (naive datetime), we can convert it this way:

dd = datetime.datetime(2012, 2, 2, 0, 0)
ams.localize(naive_dt).astimezone(pst)  # set it as 'ams' first, then convert to pst
Out[131]: datetime.datetime(2012, 2, 1, 15, 0, tzinfo=<DstTzInfo 'US/Pacific' PST-1 day, 16:00:00 STD>)

To see the difference between two timezones:

In [137]: ams.utcoffset(datetime.datetime(2012,1,1))
Out[137]: datetime.timedelta(0, 3600)

In [138]: pst.utcoffset(datetime.datetime(2012,1,1))
Out[138]: datetime.timedelta(-1, 57600)

So ams is +1H according to UTC, and pst is -8 (-1 day and +16H)

EDIT: As explained in the docs, this:

datetime(2002, 10, 27, 12, 0, 0, tzinfo=amsterdam)

will not work.

like image 166
Tisho Avatar answered Oct 18 '22 22:10

Tisho