datetime, time zone and xs:datetime

Nagy László Zsolt gandalf at shopzeus.com
Fri Aug 26 06:59:03 EDT 2016


  Hello,

I'm having problems finding the "preferrably one" way to convert a
datetime instance into an xs:datetime string.

Here is an example datetime instance with is format:

dt = datetime.now()
print(dt.isoformat()) # prints "2016-08-26 12:41:13.426081+02:00"
print(dt.strftime('%Y-%m-%dT%H:%M:%S%z')) # prints
"2016-08-26T12:41:13+0200"

The main flaw is that the xs:datetime format requires a colon. (See
http://books.xmlschemata.org/relaxng/ch19-77049.html )

The %z format does not contain that. I'm not sure when and how the %z
could be used out of the box, but probably there are datetime formats
when they are needed.

Of course, I can do a workaround:

def datetime_to_xsd_timestamp(dt):
    s = dt.strftime('%Y-%m-%dT%H:%M:%S')
    tzs = dt.strftime("%z")
    if tzs:
        s += tzs[:3] + ":" + tzs[3:]
    return s

But this does not seem to be the right way to do it. Could we have
datetime.xsdformat()? Or maybe extra format characters in strftime that
represent the hour and the minute part of the time zone offset? Or maybe
I'm not aware of some method in the standard library that converts to
this format back and forth?

Thanks,

   Laszlo






More information about the Python-list mailing list