简体   繁体   中英

Python date iso8601 format with timezone designator

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM