I have an application where I need to measure the week-number of the year, and I want all weeks to have 7 days, regardless of whether the days are in separate years.
For example, I want all the days from Dec 30, 2012 to Jan 5, 2013 to be in the same week.
But this is not straight forward to do in python, because as the datetime
documentation states here:
%U Week number of the year (Sunday as the first day of the week)
as a decimal number [00,53]. All days in a new year preceding the
first Sunday are considered to be in week 0.
I do not want 'All days in a new year preceding the first Sunday' to be considered to be in week 0. Week 0 will have less than 7 days, as will the last week of 2012.
Therefore Python returns:
import datetime
datetime.date(2012, 12, 31).strftime('%Y-%U')
>>> 2012-53
import datetime
datetime.date(2013, 01, 01).strftime('%Y-%U')
>>> 2013-00
Even though those two days are a Monday and Tuesday, respectably and should be in the same week, when a week is considered to start on Sunday and end on Saturday.
Instead, I want functionality that mirrors what MySQL does with yearweek
in mode 2 (doc here).
For example,
mysql> select yearweek('2013-01-01', 2) as week;
+--------+
| week |
+--------+
| 201253 |
+--------+
1 row in set (0.64 sec)
Note that even though the date is in 2013, the week is considered to be 201253, guaranteeing that the last week of 2012 will 7 days.
Is this already implemented in Python?
Calendar included below for reference:
December 2012
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
January 2013
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
The isoweek module provides everything you need.
From the documentation:
from isoweek import Week
w = Week(2011, 20)
print "Week %s starts on %s" % (w, w.monday())
print "Current week number is", Week.thisweek().week
print "Next week is", Week.thisweek() + 1
http://pypi.python.org/pypi/isoweek/1.1.0
I didn't find a native way to do this, so I just wrote some very simple code to test whether the week was the zero-th week, meaning that the date is in the current year but before the starting date of the first full week of the current year, and equivalently the date is in the last week of the previous year.
def get_week(date):
date = datetime.datetime.strptime(date, '%Y-%m-%d')
week = date.strftime('%Y%U')
if week[-2:] == '00':
year = week[:-2]
prev_year = int(year) - 1
week = datetime.date(prev_year, 12, 31).strftime('%Y%U')
else:
pass
return week
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With