def ISO8601Format(dt):
 isoStr = dt.strftime('%Y-%m-%dT%H:%M:%S')
 if dt.microsecond:
  isoStr += ('.%06d' % dt.microsecond).rstrip('0')
 if dt.tzinfo:
  tz = dt.strftime('%z')
 else:
  if (time.daylight and time.localtime().tm_isdst):
   utcOffset_minutes = ((- time.altzone) / 60)
  else:
   utcOffset_minutes = ((- time.timezone) / 60)
  tz = ('%+.2d%.2d' % ((utcOffset_minutes / 60), (abs(utcOffset_minutes) % 60)))
 if (tz == '+0000'):
  return (isoStr + 'Z')
 elif tz:
  return (((isoStr + tz[:3]) + ':') + tz[3:])
 else:
  return (isoStr + '-00:00')

def ISO8601Format ( dt ) : isoStr = dt . strftime ( '%Y-%m-%dT%H:%M:%S' ) if dt . microsecond : isoStr += ( '.%06d' % dt . microsecond ) . rstrip ( '0' ) if dt . tzinfo : tz = dt . strftime ( '%z' ) else : if ( time . daylight and time . localtime ( ) . tm_isdst ) : utcOffset_minutes = ( ( - time . altzone ) / 60 ) else : utcOffset_minutes = ( ( - time . timezone ) / 60 ) tz = ( '%+.2d%.2d' % ( ( utcOffset_minutes / 60 ) , ( abs ( utcOffset_minutes ) % 60 ) ) ) if ( tz == '+0000' ) : return ( isoStr + 'Z' ) elif tz : return ( ( ( isoStr + tz [ : 3 ] ) + ':' ) + tz [ 3 : ] ) else : return ( isoStr + '-00:00' )
python datetime isoformat() has the following problems: - leave trailing 0 at the end of microseconds - tz print +00:00 instead of z - missing timezone offset for datetime without tzinfo .