Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #6071

Re: Python 2.6 and timezones

References <46c24750-ac9b-4d75-835c-5403ff2ea959@d28g2000yqf.googlegroups.com> <mailman.1971.1306147689.9059.python-list@python.org> <932c351d-0dbd-4d5b-8151-e695b4b83fe1@z37g2000vbl.googlegroups.com>
Date 2011-05-23 23:33 +1100
Subject Re: Python 2.6 and timezones
From Daniel Kluev <dan.kluev@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.1975.1306154023.9059.python-list@python.org> (permalink)

Show all headers | View raw


On Mon, May 23, 2011 at 10:56 PM, loial <jldunn2000@gmail.com> wrote:
> Thanks...but being a python newbie I am struggling to understand how
> to do this.
>
> How can I use tzinfo to do the equivalent of what I do in Java, which
> is  :
>
>    TimeZone tz1 = TimeZone.getDefault();
>
>    long localOffset = tz1.getOffset(date.getTime());
>
>    TimeZone tz2 = TimeZone.getTimeZone("EST");
>
>    long remoteOffset = tz2.getOffset(date.getTime());
>

>>> from pytz import timezone, FixedOffset
>>> import time
>>> from datetime import datetime
>>> local_tz = FixedOffset(-time.timezone/60)

time.timezone returns local timezone in seconds and negative sign.
FixedOffset converts it into tzinfo object.

>>> now = datetime.now()
>>> local_tz.utcoffset(now)
datetime.timedelta(0, 36000)

utcoffset() returns timedelta object as offset. It requires datetime
object as first parameter due to weird API of base tzinfo class, but
it is not used in calculation, and you can pass any other object,
including None instead, like `local_tz.utcoffset(None)`

>>> remote_tz = timezone("EST")
>>> remote_tz.utcoffset(now)
datetime.timedelta(-1, 68400)

You can add or substract these timedelta objects directly from
datetime objects or use astimezone():

>>> now = datetime.now(local_tz)
>>> now
datetime.datetime(2011, 5, 23, 22, 41, 48, 398685, tzinfo=pytz.FixedOffset(600))
>>> now.astimezone(remote_tz)
datetime.datetime(2011, 5, 23, 7, 41, 48, 398685, tzinfo=<StaticTzInfo 'EST'>)


-- 
With best regards,
Daniel Kluev

Back to comp.lang.python | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

Python 2.6 and timezones loial <jldunn2000@gmail.com> - 2011-05-23 03:32 -0700
  Re: Python 2.6 and timezones Daniel Kluev <dan.kluev@gmail.com> - 2011-05-23 21:48 +1100
    Re: Python 2.6 and timezones loial <jldunn2000@gmail.com> - 2011-05-23 04:56 -0700
      Re: Python 2.6 and timezones Daniel Kluev <dan.kluev@gmail.com> - 2011-05-23 23:33 +1100

csiph-web