[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

Re: Time Zone application after strptime?

Jim Carroll

3/11/2008 6:01:00 PM

M.-A. Lemburg <mal <at> egenix.com> writes:

>
> On 2008-03-07 22:24, Jim Carroll wrote:
> > It's taken me a couple of hours to give up on strptime
> > with %Z for recognizing
> > time zones... but that still leaves me in the wrong zone:
> >
> > How can I use the "PST" (or any other time zone name)
> > to adjust dt by the
> > correct number of hours to get it into UTC before storing in MySQL?
>
> You could try mxDateTime's parser. It will convert most timezones
> into UTC for you:
>
> >>> from mx.DateTime import *
> >>> DateTimeFrom('10:29:52 PST, Feb 29, 2008')
> <mx.DateTime.DateTime object for '2008-02-29 18:29:52.
> 00' at 2afdc7078f50>
>

Unfortunately, mx.DateTime also ignores the time zone. If
I parse the PST time, and ask for the result's time zone it
gives me my local time zone.

I have had some luck with dateutil:

>>> import dateutil.parse as p
>>> p.parse("10:29:52 Feb 29, 2008 PST")
datetime.datetime(2008, 2, 29, 10, 29, 52)

and if I hand it a list of time zones, it does the right thing

>>> zones = {"PST": -8*60*60}
p.parse("10:29:52 Feb 29, 2008 PST", tzinfos=zones)
datetime.datetime(2008, 2, 29, 10, 29, 52, tzinfo=tzoffset('PST', -28800))

But I cannot figure out how to get dateutil to use the
zoneinfo file that it includes in its own package. It has a
zoneinfo-2007k.tar.gz right in the package, and a class
to parse the binary zoneinfo, but no clear way to get it to
parse its own file and use those during the parsing.




1 Answer

attn.steven.kuo@gmail.com

3/12/2008 2:30:00 AM

0

On Mar 11, 11:00 am, Jim Carroll <j...@maplesong.com> wrote:

(snipped)
>
> p.parse("10:29:52 Feb 29, 2008 PST", tzinfos=zones)
> datetime.datetime(2008, 2, 29, 10, 29, 52, tzinfo=tzoffset('PST', -28800))
>
> But I cannot figure out how to get dateutil to use the
> zoneinfo file that it includes in its own package. It has a
> zoneinfo-2007k.tar.gz right in the package, and a class
> to parse the binary zoneinfo, but no clear way to get it to
> parse its own file and use those during the parsing.


Try the pytz module.

import datetime
import pytz
import time

utc = pytz.utc
zones = { 'PST': pytz.timezone('US/Pacific'), }

aware_dt = datetime.datetime(tzinfo=zones['PST'],
*time.strptime("10:29:52 Feb 29, 2008 PST",
"%H:%M:%S %b %d, %Y %Z")[0:6])
print aware_dt.strftime("%H:%M:%S %b %d, %Y %Z")
print utc.normalize(aware_dt.astimezone(utc)).strftime("%H:%M:%S %b
%d, %Y %Z")

# 10:29:52 Feb 29, 2008 PST
# 18:29:52 Feb 29, 2008 UTC

--
Hope this helps,
Steven