[Tutor] Readable date arithmetic

Dave Angel davea at ieee.org
Thu Nov 19 18:06:03 CET 2009


Kent Johnson wrote:
> On Thu, Nov 19, 2009 at 1:14 AM, Stephen Nelson-Smith
> <sanelson at gmail.com> wrote:
>   
>> I have the following method:
>>
>> def get_log_dates(the_date_we_want_data_for):
>>  t =ime.strptime(the_date_we_want_data_for, '%Y%m%d')
>>  t2 =atetime.datetime(*t[:-2])
>>     
>
> Use datetime.datetime.strptime() to save a step:
> t2 =atetime.datetime.strptime(the_date_we_want_data_for, '%Y%m%d')
>
>   
>>  extra_day =atetime.timedelta(days=1)
>>  t3 =2 + extra_day
>>     
>
> t2 +=atetime.timedelta(days=1)
>
>   
>>  next_log_date =3.strftime('%Y%m%d')
>>  return (the_date_we_want_data_for, next_log_date)
>>
>> Quite apart from not much liking the t[123] variables, does date
>> arithmetic really need to be this gnarly?
>>     
>
> Yes, pretty much. Convert the string to a date-aware object, increment
> the date, convert back to a string.
>
>   
>> How could I improve the above, especially from a readability
>> perspective?
>>     
>
> Above changes improve readability IMO.
>
> Kent
>
>   
My opinion is that these three things don't usually belong in the same 
function.  You should be converting incoming dates to datetime format, 
and only convert back when you're ready to output something that has to 
be human-readable text.  That way you avoid double-conversions, and can 
localize problems such as dealing with multiple timezones or daylight 
savings.  When you're passing dates around the program, use a simple, 
self-describing format, such as datetime.

YMMV,
DaveA



More information about the Tutor mailing list