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

Wolfgang Maier wolfgang.maier at biologie.uni-freiburg.de
Wed Aug 6 17:19:30 CEST 2014


On 06.08.2014 16:14, Ethan Furman wrote:
> On 08/04/2014 06:39 PM, Steven D'Aprano wrote:
>> On Mon, Aug 04, 2014 at 10:56:56PM +0200, Wolfgang Maier wrote:
>> [...]
>>> it does hold true in 3.x, but the documented behavior is slightly more
>>> complex (I assume also in 2.x):
>>>
>>> datetime.__str__()
>>>      For a datetime instance d, str(d) is equivalent to d.isoformat('
>>> ').
>>
>> 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.
>
> What are the downsides of:
>
> dt = datetime.datetime.now()    # assuming this works ;)
> sdt = str(dt)
> ndt = datetime.datetime(std)
> print(dt == ndt)
> #True
>

I'll refrain from mentioning "explicit is better than implicit" ;)

It's just that it seems to be a design pattern of the datetime class to 
provide alternative constructors as classmethods instead of doing magic 
things in __new__ . There are fromtimestamp and utcfromtimestamp 
already, and you can think of datetime.now() the same way. After all, 
you could decide to have this called when datetime() is called without 
an argument.
I guess there are just too many different things that *could* make sense 
to pass to __new__ and to be treated implicitly.

Wolfgang



More information about the Python-ideas mailing list