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?
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'
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With