[Python-ideas] strptime without second argument as an inverse to __str__

Jonas Wielicki j.wielicki at sotecware.net
Tue Aug 5 23:28:22 CEST 2014


On 05.08.2014 23:22, Wolfgang Maier wrote:
> On 05.08.2014 03:39, Steven D'Aprano wrote:
>>
>> Since str(d) is documented to use a well-defined format, then I agree
>> that it makes sense to make the second argument to d.strptime optional,
>> and default to that same format. The concern I had was the sort of
>> scenario Skip suggested: I might write out a datetime object as a string
>> on one machine, where the format is X, and read it back elsewhere, where
>> the format is Y, leading to at best an exception and at worse incorrect
>> data.
>>
>> +1 on the suggestion.
>>
> 
> After looking a bit into the code of the datetime module, I am not
> convinced anymore that strptime() is the right place for the
> functionality for the following reasons:
> 
> 1) strptime already has a clear counterpart and that's strftime.
> 
> 2) strftime/strptime use explicit format strings, not any more
> sophisticated parsing (as would be required to parse the different
> formats that datetime.__str__ can produce) and they try, intentionally,
> to mimick the behavior of their C equivalents.
> 
> In other words, strftime/strptime have a very clear underlying concept,
> which IMO should not be given up just because we are trying to stuff
> some extra-functionality into them.
> 
> That said, I still think that the basic idea - being able to
> reverse-parse the output of datetime.__str__ - is right.
> 
> I would suggest that a better place for this is an additional
> classmethod constructor (the datetime class already has quite a number
> of them). Maybe fromisostring() could be a suitable name ?

Maybe rather fromisoformat(), to stay analogous with the formatting method?

> With this you could even pass an extra-argument for the date-time
> separator just like with the current isoformat.
> This constructor would then be more like a counterpart to
> datetime.isoformat(), but it could simply be documented that calling it
> with fromisostring(datestring, sep=" ") can be used to parse strings
> written with datetime.str().
> 
> -1 on the specifics of the proposal,
> +1 on the general idea.

+1 for this rating.

> 
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/



More information about the Python-ideas mailing list