Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python date iso8601 format with timezone designator

Tags:

python

I'm sending some dates from server that has it's time in gmt-6 format, but when i convert them to isoformat i don't get the tz designator at the end.

I'm currently setting the date like this:

date.isoformat()

but I'm getting this string: 2012-09-27T11:25:04 without the tz designator.

how can I do this?

like image 799
madprops Avatar asked Sep 27 '12 18:09

madprops


2 Answers

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'
like image 185
David Wolever Avatar answered Oct 30 '22 23:10

David Wolever


It is much easier to deal with dates with a specialized module such as arrow or delorean

>>> import arrow
>>> arrow.now().isoformat()
'2020-11-25T08:10:39.672624+01:00'
like image 29
WoJ Avatar answered Oct 31 '22 00:10

WoJ