Timezone and ISO8601 struggles with datetime and xml.utils.iso8601.parse

skip at pobox.com skip at pobox.com
Fri Sep 9 13:57:53 EDT 2005


    Samuel> mydatetime = datetime.datetime(year, month, day, hour, minute)
    Samuel> strtime    = mydatetime.isoformat()

Take a look at the utcoffset method of datetime objects.

    Samuel> The second problem has to do with the ISO8601 parser, which
    Samuel> raises the following error:

    Samuel> ----------------------
    Samuel> Traceback (most recent call last):
    Samuel>   File "./timetest.py", line 16, in ?
    Samuel>     mytimestamp = xml.utils.iso8601.parse(strtime)
    Samuel>   File "/usr/lib/python2.4/site-packages/_xmlplus/utils/iso8601.py",
    Samuel> line 22, in parse
    Samuel>     raise ValueError, "unknown or illegal ISO-8601 date format: " + `s`
    Samuel> ValueError: unknown or illegal ISO-8601 date format:
    Samuel> '2005-07-22T10:30:00'
    Samuel> ----------------------

    Samuel> Why does it fail to parse the value returned by the datetime
    Samuel> object, and how can I create a parseable time from the datetime
    Samuel> object?

One possibility might be that datetime objects stringify with microseconds
included:

    >>> t = datetime.datetime.now()
    >>> t
    datetime.datetime(2005, 9, 9, 12, 52, 38, 677120)
    >>> strtime = t.isoformat()
    >>> strtime
    '2005-09-09T12:52:38.677120'

You can try stripping the microseconds first:

    >>> time.strptime(strtime, "%Y-%m-%dT%H:%M:%S")
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
      File "/Users/skip/local/lib/python2.5/_strptime.py", line 295, in strptime
        raise ValueError("unconverted data remains: %s" %
    ValueError: unconverted data remains: .677120
    >>> time.strptime(strtime.split(".")[0], "%Y-%m-%dT%H:%M:%S")
    (2005, 9, 9, 12, 52, 38, 4, 252, -1)

Skip



More information about the Python-list mailing list