I have a function which is supposed to build a header for a calendar like so:
' Sun Mon Tue Wed Thu Fri Sat '
It takes a isoweekday (one of '#Monday' 1, 2, 3, 4, 5, 6, 7 '#Sunday').
Here is the code:
@staticmethod
def _isoweekday_to_str(isoweekday):
isoweekday = isoweekday - 1
isoweekday = str(isoweekday)
x = datetime.strptime(isoweekday, '%w')
return x.strftime('%a')
TEXT_CAL_MONTH_WEEK_HEADER = ""
iter_isoweekday = week_start
for _ in range(0,7):
TEXT_CAL_MONTH_WEEK_HEADER += self._isoweekday_to_str(iter_isoweekday).rjust(TEXT_CAL_CELL_WIDTH, " ")
if iter_isoweekday != 7:
iter_isoweekday += 1
else:
iter_isoweekday = 1
The output I'm getting, when passing in 4 as the week start, is:
' Mon Mon Mon Mon Mon Mon Mon '
it should be:
' Thu Fri Sat Sun Mon Tue Wed '
I'm really, really not sure what's going on. I think it's either something to do with the way variables are assigned, string mutation, or the datetime library.
UPDATE: it appears that datetime.strptime is the problem. No matter what I pass in, I get datetime(1900, 1, 1, 0, 0) back... which, you guessed it, was a Monday.
Help?
You can get the localised days of the week from the calendar module:
>>> import calendar
>>> list(calendar.day_name)
['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
Or the abbreviated names, using calendar.day_abbr
:
>>> ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
See the documentation if you need other locales.
Obviously, the module can produce whole calendars:
>>> print calendar.TextCalendar().formatmonth(2016, 1)
January 2016
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