Thursday, June 27, 2013

Calculating week range based on a timestamp

When someone asks you to create a weekly report (pulling some data from an arbitrary database), you'll be faced with the task of coming up with a week range first: the start and end date for a given week. You're given a Unix timestamp. Assuming that a week starts on Monday midnight and knowing that Unix epoch started at on a Thursday 00:00:00 UTC on 1 January 1970, here is a simple way of coming up with a week range:
# weekrange.py
DAY_IN_SECONDS = 24 * 60 * 60
WEEK_IN_SECONDS = 7 * DAY_IN_SECONDS

def get_week_range(timestamp):
    """Return start and end of the week surrounding the timestamp."""
    # Get previous Thursday midnight.
    secs_since_previous_thu = timestamp % WEEK_IN_SECONDS
    previous_thursday = timestamp - secs_since_previous_thu
    # Adjust start of the week by three days.
    week_start = previous_thursday - 3 * DAY_IN_SECONDS
    week_end = week_start + WEEK_IN_SECONDS - 1
    return (week_start, week_end)
Verification; get the week range of the week from a fortnight ago in an interactive shell.
$ ipython

In [1]: import weekrange

In [2]: import time

In [3]: weekrange.get_week_range(time.time() - 2 * weekrange.WEEK_IN_SECONDS)
Out[3]: (1370822400.0, 1371427199.0)

In [4]: !date -u -d@1370822400.0
Mon Jun 10 00:00:00 UTC 2013

In [5]: !date -u -d@1371427199.0
Sun Jun 16 23:59:59 UTC 2013

No comments:

Post a Comment