Reputation: 16966
I am writing a little utility function in Python which returns a boolean, indicating whether today is in the first week of the month.
This is what I have so far:
import calendar
import time
y, m = time.localtime(time.time())[:2]
data = calendar.month(y, m)
In [24]: type(temp)
Out[24]: <type 'str'>
In [25]: print temp
-------> print(temp)
July 2010
Mo Tu We Th Fr Sa Su
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
I want to pack this string into a list of lists. Actually, it's only the first row that I want, since it is the first week, but I could generalize the function so that it allows me to check whether we are in the nth week, where 1 < n < 5 (depending on the month of course).
Once I have a list of lists I then intend to check if the current day is an element in the list.
Can anyone show how I can get the output from the calendar.month() method into a list of lists?
Last but not the least, I may be reinventing the wheel here. If there is an inbuilt way of doing this (or maybe a more Pythonic way of doing this) someone please let me know.
Upvotes: 5
Views: 3623
Reputation: 33716
Here is a total solution using the standard library.
import calendar
import datetime
def in_first_week(today):
"""Expects a datetime object"""
weeks = calendar.monthcalendar(today.year, today.month)
firstweek = weeks[0]
return today.day in firstweek
today = datetime.date.today()
# => datetime.date(2010, 7, 1)
print in_first_week(today)
# => True
then = datetime.date(2010,7,10)
print in_first_week(then)
# => False
Upvotes: 4
Reputation: 192921
Here's a simple function which will tell you whether today is in the first week of the month:
from datetime import date
def first_week():
today = date.today()
return today.weekday() - today.day >= -1
This is simpler than processing the output of a call into the calendar library; simply take the day of the week in numeric form (which starts at 0) and then subtract the day of the month (which starts at 1). If the result is at least -1, you're in the first week.
Upvotes: 5
Reputation: 21
calendar.monthcalendar(2010,7)
This returns a list of lists as such:
[[0, 0, 0, 1, 2, 3, 4], [5, 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17, 18], [19, 20, 21, 22, 23, 24, 25], [26, 27, 28, 29, 30, 31, 0]]
Upvotes: 2