YADTR (Yet Another DateTime Rant)

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Mar 27 01:16:57 CET 2014


On Wed, 26 Mar 2014 19:25:45 -0400, Dennis Lee Bieber wrote:

> On Tue, 25 Mar 2014 20:58:27 -0400, Roy Smith <roy at panix.com> declaimed
> the following:
> 
>>One of my roles on this newsgroup is to periodically whine about
>>stupidities in the Python datetime module.  This is one of those times.
>>
>>I have some code which computes how long ago the sun set.  Being a nice
>>pythonista, I'm using a timedelta to represent this value.  It would be
>>difficult to imagine a less useful default way to print a timedelta:
>>
>>previous sunset: -1 day, 22:25:26.295993
>>
>>The idea of str() is that it's supposed to return a human-friendly
>>representation of a value.  Humans do not say things like, "The sun set
>>1 day ago plus 22 hours and 25 minutes".
> 
> 	Makes sense to me -- the key being time DELTA... IE, a difference 
> from some (unspecified) instance in time...
> 
> 	If you want an instance of time, you need to add some known 
> instance and the delta value.


I think you have missed the point of the rant. Roy is not ranting that he 
has a timedelta. He wants a timedelta. He is ranting that the timedelta 
displays in a totally unintuitive fashion. Paraphrasing:

"the previous sunset was (one day less 22 hours and 25 minutes) ago"

instead of 

"the previous sunset was (1 hour and 35 minutes) ago"

where the parts in the brackets come directly from the timedelta object.

I think that you misread Roy's example as:

"1 day plus 22 hours 25 minutes ago"

instead of:

"1 day ago plus 22 hours 25 minutes"

(that is, 22 hours and 25 minutes after 1 day ago).

The problem here, I believe, is that there are two ways of interpreting 
remainders for negative numbers. Dividing -5 by 2 can give either -2 with 
remainder -1, or -3 with remainder +1.

Mathematically, it is *usually* more useful to go with the version with 
the positive remainder, and that's what Python does. But I think it's the 
wrong choice for timedelta. Let's take a simple example: a timedelta of 
30 hours. What's that in days and hours?

py> divmod(30, 24)
(1, 6)

That makes perfect intuitive sense: 30 hours is 1 day with 6 hours 
remaining. In human-speak, we'll say that regardless of whether the 
timedelta is positive or negative: we'll say "1 day and 6 hours from now" 
or "1 day and 6 hours ago". But when we specify the sign:

py> divmod(-30, 24)
(-2, 18)

If an event happened 30 hours ago, it is correct to say that it occurred 
"18 hours after 2 days ago", but who talks that way?




-- 
Steven D'Aprano
http://import-that.dreamwidth.org/



More information about the Python-list mailing list