datetime iso8601 string input

Magnus Lycka lycka at carmen.se
Thu Mar 23 08:35:14 EST 2006


skip at pobox.com wrote:
> Why not
> 
>     dt = datetime.datetime(*time.strptime(s, "%Y-%m-%dT%H:%M:%S")[0:6])
> 
> ?

Maybe due to neglection of the 7th commandment?
Most of the other commandments can be ignored while
coding Python, but the 7th certainly applies here.

http://www.lysator.liu.se/c/ten-commandments.html

As I've written before, the ISO 8601 spec contains
many variations in date formats. Making a full ISO
8601 parser is probably possible if we ignore time
deltas, but it's hardly worth the effort. Writing
something that parses a few percent of the possible
ISO 8601 messages and calling that an ISO 8601
parser seems silly to me.

With code like Skip's above it's obvious what kind
of strings are handled. In typical applications, one
such format is enough, and this needs to be properly
specified. In a recent case I wrote the spec like
this:

"The timestamp shall be an ISO 8601 combination of
UTC date and time with complete representation in
extended format, with representation of fractions
of seconds with up to six decimals preceeded by a
full stop as decimal sign.
E.g. 2005-06-20T13:42:55.2425Z"

Despite my verbosity here, someone who didn't follow
the example, would still be able to write ISO 8601
strings following the requirements above that we
won't parse, since I didn't actually write that dates
should be written as year-month-day.

For a brief summary of some of the allowed variation
see http://hydracen.com/dx/iso8601.htm



More information about the Python-list mailing list