The "beaty" of date arithmetic
Hans-Joachim Widmaier
hjwidmaier at web.de
Thu Jan 23 02:52:01 EST 2003
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 ...
Thanks for any thoughts,
Hans-Joachim
More information about the Python-list
mailing list