Python date iso8601 format with timezone designator

You're not getting the timezone designator because the datetime is not aware (ie, it doesn't have a tzinfo):

>>> import pytz
>>> from datetime import datetime
>>> datetime.now().isoformat()
'2012-09-27T14:24:13.595373'
>>> tz = pytz.timezone("America/Toronto")
>>> aware_dt = tz.localize(datetime.now())
>>> datetime.datetime(2012, 9, 27, 14, 25, 8, 881440, tzinfo=<DstTzInfo 'America/Toronto' EDT-1 day, 20:00:00 DST>)
>>> aware_dt.isoformat()
'2012-09-27T14:25:08.881440-04:00'

In the past, when I've had to deal with an unaware datetime which I know to represent a time in a particular timezone, I've simply appended the timezone:

>>> datetime.now().isoformat() + "-04:00"
'2012-09-27T14:25:08.881440-04:00'

Or combine the approaches with:

>>> datetime.now().isoformat() + datetime.now(pytz.timezone("America/Toronto")).isoformat()[26:]
'2012-09-27T14:25:08.881440-04:00'

Tags:

Python