8

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?

Andy Hayden
  • 359,921
  • 101
  • 625
  • 535
madprops
  • 3,909
  • 5
  • 34
  • 42
  • [This answer on another thread](https://stackoverflow.com/a/28147286/1717535) has a section with "UTC to ISO 8601 with TimeZone information (Python 3)". – Fabien Snauwaert Jul 06 '22 at 11:12

2 Answers2

10

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'
A T
  • 13,008
  • 21
  • 97
  • 158
David Wolever
  • 148,955
  • 89
  • 346
  • 502
1

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'
WoJ
  • 27,165
  • 48
  • 180
  • 345