ISO with timezone

Nicholas F. Fabry nick.fabry at coredump.us
Tue Jan 29 00:10:23 EST 2008


Hello, nik.

On Jan 28, 2008, at 21:03, nik wrote:

> Hi,
>
> How does one express the time in ISO format with the timezone
> designator?
>
> what I want is YYYY-MM-DDThh:mm:ss.sTZD
>
>> From the documentation I see:
>>>> from datetime import tzinfo, timedelta, datetime
>>>> class TZ(tzinfo):
> ...     def utcoffset(self, dt): return timedelta(minutes=-399)
> ...
>>>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
> '2002-12-25 00:00:00-06:39'
>
> and I've also figured out:
>>>> datetime.datetime.fromtimestamp(time.time()).isoformat()[:-3]
> '2008-01-23T11:22:54.130'
>
> But can't figure out how to fit them together.
>

There is nothing there to 'fit together' - in the first example given,  
the datetime object has no time component specified, so it fills in  
default vaules of zero.  The following should make this clear:

 >>> your_time = datetime(2008, 2, 29, 15, 30, 11, tzinfo=TZ())
 >>> print your_time
2008-02-29 15:30:11-05:00
 >>> print your_time.isoformat('T')
2008-02-29T15:30:11-05:00

If you wish to append the NAME of the tzinfo object instead of its  
offset, that requires a bit more playing around (along with a properly  
defined tzinfo object - check out dateutil or pytz for a concrete  
implementation of tzinfo subclasses (i.e. timezones)), but the  
following would work:

 >>> print your_time.strftime('%Y-%m-%dT%H:%M:%S %Z')
2008-02-29T15:30:11 EST

For details on how the .strftime method works, see Python Standard  
Library, Section 14.2.

I hope this helps!

Nick Fabry





> Thank you,
> Nik
> -- 
> http://mail.python.org/mailman/listinfo/python-list




More information about the Python-list mailing list