user2253332
user2253332

Reputation: 827

How to tell what week it is in Python?

So say I have a date, for example, 08/27/2014, and I want to find out what week it is (like if it's the first week, or the second week, or the third week. In this case, it would the fourth week), assuming that a new week starts on Sunday. Does anyone have any ideas as to how to do this?

Upvotes: 0

Views: 79

Answers (2)

André Laszlo
André Laszlo

Reputation: 15537

Week as a service:

import urllib2
import re

def week():
    response = urllib2.urlopen('http://vecka.nu')
    html = response.read()
    match = re.search('datetime="(\d+)-W(\d+)"', html, re.M)
    if match:
        return int(match.group(2))

Just kidding! Although, this is how I usually check which week it is ;)

Upvotes: 0

giant_teapot
giant_teapot

Reputation: 717

You could do it simply using the isocalendar function (https://docs.python.org/2/library/datetime.html#datetime.date.isocalendar).

If your week starts on Wed instead of Mon, you just need a little logic get the correct number (-1 if you're on a Mon or Tue).

EDIT : saw you edit after posting, but still works, just need a different logic (+1 if you're on a Sunday)

Upvotes: 2

Related Questions