## Extended Format for Date Parsing in Python

From: andrew cooke <andrew@...>

Date: Thu, 20 Jun 2013 21:08:04 -0400

In simple-date (https://github.com/andrewcooke/simple-date) I use the standard
Python date format (almost - %Z is actually %Z! in the notation I will
introduce below).  That means that SimpleDateParser has to try many different
alternatives when parsing dates (it contains a list of different formats and
tries them in turn until one works).

A few extensions would allow significantly fewer attempts to be made:

- optional matching, marked by a trailing ?

- nestable grouping and alternatives, like (A|B|C)

- matching of variable space with $* and$+ (0- or 1-or-more)

- modified matchers for textual day, month, and timezone that accept any
string (rather than the set of valid values from the locale).  this
could be indicated by a trailing !

- an additional offset timezone with a colon between hours and minutes, \$:

This would allow

'%Y-%m-%d %H:%M', '%Y-%m-%d', '%Y')

where add_timezone repeats that list for each (or no) timezone matcher, with

'%Y(-%m(-%d((%+|T)%H:%M(:%S(.%f)?)?))?)?%*(%Z!|%z|%:)?'

which is certainly more opaque, but also significantly more powerful.

The main problem with this is that it cannot also be used, in general, for
printing.  But when it is used for parsing then the ambiguities are resolved
(if it matches).  So we could generate the "equivalent format" for a
successful match, which would be useful for printing values in the style as
they were originally parsed (this, incidentally, is why I want to modify
textual matches, rather than simply have an "ignored word" matcher).

Most of the above is quite easy (the current code works by expanding the
format into a regular expression, so %Y becomes (?P<Y>\d\d\d\d), for example).
The main challenge, I think, is the "equivalent format" - whether it is unique
and efficient.

Andrew