datetime and tzinfo

Tim Peters tim.peters at gmail.com
Thu Sep 16 14:45:21 EDT 2004


[John Hunter]
> I am using the tzinfo classes from the datetime docs, eg UTC,
> USTimeZone, and the instantiations Pacific, Central, Eastern, etc.  I
> would like to take a datetime instance in the UTC timezone and
> construct the equivalent in another time zone.
>
> Eg, if I am given dt1 in the example below, and the timezone Central
> 
>  dt1 = datetime(2004, 9, 12, 14, 22, 24, tzinfo=UTC())
>
> I would like to construct the datetime instance dt2
>
>  dt2 = datetime(2004, 9, 12, 9, 22, 24, tzinfo=Central)
>
> which is the same time in a different timezone.
> 
>    >>> dt1 = datetime(2004, 9, 12, 14, 22, 24, tzinfo=UTC())
>    >>> dt2 = datetime(2004, 9, 12, 9, 22, 24, tzinfo=Central)
>    >>> dt1-dt2
>    datetime.timedelta(0)
>
> I've read through the docs at
> http://www.python.org/doc/2.3.2/lib/datetime-tzinfo.html but none of
> the methods looked just right.
>
> Is there an easy/right way to do this?

Yes, you're just looking in a, umm, suboptimal part of the docs. 
Since you're trying to construct a new datetime.datetime, the docs for
datetime.datetime are the place to look.  It's a one-liner:

dt2 = dt1.astimezone(Central)

After that,

>>> print repr(dt2)
datetime.datetime(2004, 9, 12, 9, 22, 24, tzinfo=Central)
>>> print dt1 - dt2
0:00:00
>>> print repr(dt2.astimezone(Eastern))
datetime.datetime(2004, 9, 12, 10, 22, 24, tzinfo=Eastern)

That is, you don't *have* to go thru UTC first; you can start and end
in any time zones.



More information about the Python-list mailing list