Thursday, March 13, 2008

Calculating Weekdays in Python

Calculating weekdays is simple for human being. But, it isn't for a computer. The task requires that the logic understands calendar due to adding/subtracting dates. Doomsday algorithm is needed to get which weekday for a given day.
Python has two time packages. time and datetime. time package works like standard C library package except its basic representation is so called time-tuple rather than epoch. ( it knows how to convert to epoch ) datetime provides 1) higher level interface, 2) capability to manipulate dates, and 3) compatibility to time package. So, working with datetime is the most cases.
Hey, let's just see the code.

from datetime import timedelta, date
def weekdays(givenDate):
  start = givenDate if givenDate else
  start = start - timedelta(start.weekday())
  end = start + timedelta(days=5)
  return start, end

Pretty simple. Now, we can use some decorator to make it useful. For example, to provide postgresql where clause, we can write like this.

def pgsqlRangeWks(givenDate=None):
  fmt = '%Y-%m-%d %H:%M'
  start, end = weekdays(givenDate)
  return "ts > '%s' and ts < '%s'" % \
    ( start.strftime(fmt), end.strftime(fmt))

Again, python is well balanced language in performance and robustness.

1 comment:

Raymond said...

I found this page is a good landing page of my blog. I need to clarify one thing. Decorator is 'Decorator design pattern', not the actual python decorator.