I am trying to get a date based on a number of the week, but there are some annoyances.
The date.weekday()
returns the day of the week where 0 in Monday and 6 is Sunday.
The %w
directive of date.strftime()
and date.strptime()
uses the 0 for Sunday and 6 for Saturday.
This causes some really annoying issues when trying to figure out a date given a week number from date.weekday()
.
Is there a better way of getting a date from a week number?
EDIT:
Added the example.
import datetime
original_date = datetime.date(2014, 8, 24)
week_of_the_date = original_date.isocalendar()[1] # 34
day_of_the_date = original_date.isocalendar()[2] # 7
temp = '{0} {1} {2}'.format(*(2014, week_of_the_date, day_of_the_date-1))
date_from_week = datetime.datetime.strptime(temp, '%Y %W %w')
week_from_new_date = date_from_week.isocalendar()[1] # 35!!
EDIT 2:
I ultimately put the date stuff in the view (using jQuery UI), it has more consistent notions of weeks.
I think the Sunday vs. Monday distinction between weekday
and strftime
using %W
is moot - you could use isoweekday
to get those to line up, or %U
in strftime
if you wanted Sunday as the first day of the week. The real problem is that strftime
, based on the underlying C function, determines the first week of the year differently than the ISO definition. With %W
the docs say: " All days in a new year preceding the first Monday are considered to be in week 0". ISO calendars count the week containing the first Thursday as the first week, for reasons I do not understand.
Two ways I found to work with ISO weeks, either just getting datetime.date
instances back or supporting a variety of operations, are:
timedelta
approach: What's the best way to find the inverse of datetime.isocalendar()?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.