[Tutor] Readable date arithmetic
Kent Johnson
kent37 at tds.net
Thu Nov 19 12:41:40 CET 2009
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 = time.strptime(the_date_we_want_data_for, '%Y%m%d')
> t2 = datetime.datetime(*t[:-2])
Use datetime.datetime.strptime() to save a step:
t2 = datetime.datetime.strptime(the_date_we_want_data_for, '%Y%m%d')
> extra_day = datetime.timedelta(days=1)
> t3 = t2 + extra_day
t2 += datetime.timedelta(days=1)
> next_log_date = t3.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
More information about the Tutor
mailing list