PEP 321: Date/Time Parsing and Formatting

Paul Moore pf_moore at yahoo.co.uk
Tue Nov 18 16:29:40 EST 2003


"A.M. Kuchling" <amk at amk.ca> writes:

> I'm lukewarm about CVS or tar-style times ("12 hours ago" "yesterday"). They
> may be good command-line user interface, because you don't need to look up
> the current time and then figure out what time 18 hours ago was, but writing
> such command-line UIs probably isn't very common.

Hmm, yes. The more I think about it, the more this feels like YAGNI.
Although "now" is something I use in cvs (cvs export -D now). But
special-casing that in user code isn't exactly hard.

What *does* bug me about strptime, though, is its behaviour with
regard to delimiters:

>>> strptime("12/07/2003", "%d/%m/%Y")
(2003, 7, 12, 0, 0, 0, 5, 193, -1)
>>> strptime("12-07-2003", "%d/%m/%Y")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "C:\Apps\Python\lib\_strptime.py", line 424, in strptime
    raise ValueError("time data did not match format:  data=%s  fmt=%s" %
ValueError: time data did not match format:  data=12-07-2003  fmt=%d/%m/%Y

This is unnecessarily hostile when it comes to user input.

I think, for parsing of machine-generated date strings (ie, ones with
a strict format) strptime is pretty much just what you want. In that
situation, strictness is a distinct advantage.

User input, or any other form of non-strict parsing, is a very
different problem. I'm not sure that there is a good answer there. Too
much depends on the environment, and user expectations.

Maybe preprocessing is the answer here:

    strptime(re.sub(r'\W', '/', userinput), '%d/%m/%Y')

Get beyond that, and you do need something like Gustavo's parse()
function (and you hit all the really nasty issues, like unguessable
DD/MM/YYYY vs MM/DD/YYYY conflicts...)

Maybe I've just convinced myself that dateutil.parser.parse, plus
(a datetime-returning) strptime, plus a little bit of "get off your
backside and code it yourself" is enough.

Paul.
-- 
This signature intentionally left blank




More information about the Python-list mailing list