The "beaty" of date arithmetic

John Roth johnroth at
Mon Jan 27 20:54:31 CET 2003

"Hans-Joachim Widmaier" <hjwidmaier at> wrote in message
news:6e990e29.0301222352.2ebb5c1e at
> Hello, my knowledgeable and helpful pythonistas! (A little flattery
> can't hurt :))
> I have a small program sitting in my FvwmButtons that allows me to
> connect and disconnect to the Internet. It shows me the accumulated
> time and volume as well as  a xload-like graph for the transfer speed.
> But this is just to give some context, so you can deduce what I'm
> after even if my explanation in this not-my-mother-language ain't good
> enough.
> Here goes: The accounting is done by months starting at a given day.
> Now I want to write a summary line in my log file (for the previous
> month) whenever a new accounting month starts. So I wrote a function
> that returns me the first and last day of a month interval which
> contains a certain time ("previous" thus means "month with any online
> time at all"). This would be easy if there wasn't the possibility for
> "first day" being 1 -- the day before that isn't just "n-1".
> Now here's (finally) my solution:
> --------------------------------------------------------
> def getDateInterval(ttime, fday):
>     """Return a month-interval starting at day |fday| and including
> |ttime|."""
>     start = list(time.localtime(ttime))
>     # Calculate first day
>     if start[2] < fday:
> # Must be last month
> start[1] -= 1
> if start[1] < 1:
>     start[1]  = 12
>     start[0] -= 1
>     # The last day is the day before next month's first day
>     start[8] = -1 # set DST to unknown
>     start[2] = fday
>     end = start[:]
>     end[1] += 1
>     if end[1] > 12:
> end[1]  = 1
> end[0] += 1
>     end = time.localtime(time.mktime(end) - 86400)
>     return start[:3], end[:3]
> --------------------------------------------------------
> All I'm asking for is: Is there a way to do it that's not as butt-ugly
> as this?
> Somehow it looks pathetic to me ...

What's even uglier is that you're mixing spaces and tabs for
How do I know? Outlook Express completely ignores tabs, so many
of your lines are incorrectly indented. I'm sure that's not how  your
looks like on your machine.

As Tim comments, there are no universal answers when it comes
to the "fuzzy" areas of date arithmetic. What you want is completely
application dependent. Any package that tries to give you a universal
answer is going to be wrong for someone, and most likely for a
lot of someones.

What I usually do is convert dates to astronomical days and then
do the arithmetic. (Astronomical days begin at 0 for some day
in 4700 BC, and count up from there.) Months are 30.6 days and
years are 365.2425 days. You can get awfully close, which is quite
good enough for me.

John Roth

> Thanks for any thoughts,
> Hans-Joachim

More information about the Python-list mailing list