Python iso8601 date format with timezone pointer

I am sending several dates from a server that has time in gmt-6 format, but when I convert them to isoformat, I do not get the tz notation at the end.

I am currently setting the date as follows:

date.isoformat() 

but I get this line: 2012-09-27T11:25:04 without the tz pointer.

How can i do this?

+5
source share
1 answer

You do not get a timezone pointer because datetime does not know (that is, it does not have 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' 

Last year, when I was dealing with an unsuspecting datetime that I know to represent time in a particular time zone, I just added a time zone:

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

Or combine approaches with:

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

Source: https://habr.com/ru/post/1436675/


All Articles