Reputation: 429
I need to get the week of year starting on sunday. The default ISO Week starts on monday, but my requirement is to get the sunday as the start of week.
for instance 2019-01-06 is a sunday and it should be week 2.
i did try
t1.strftime("%U")
but the problem is it retuns 0 for all days in a new year preceding the first Sunday and starts the week count from first sunday of the year.
Thanks for the help in advance.
Upvotes: 2
Views: 890
Reputation: 452
Sharing my code for a slightly different implementation than yours. I take into account that the first day of the year could belong to last year's week. Although, you could very well adjust this code to your needs.
The piece of code given below returns the year_wk for any 'given_date' and
where the week starts from any day_no (It is 4 ie Friday in the code below)
import math as mt
import datetime as dt
def get_first_date_year(year, day_no):
d1 = dt.date(year, 1, 1)
return d1 + dt.timedelta((day_no - d1.weekday())%7)
def get_yearwk_from_date(given_date, day_no):
first_date = get_first_date_year(given_date.year, day_no)
if (given_date < first_date):
first_date = get_first_date_year(given_date.year-1, day_no)
return first_date.year*100 + mt.ceil(((given_date - first_date).days+1)/7)
FRIDAY = 4
for i in range(20):
given_date = dt.date(2018, 12, 23) + dt.timedelta(days=i)
year_wk = get_yearwk_from_date(given_date, FRIDAY)
print("Date: "+str(given_date)+", YearWeek: "+str(year_wk))
Output:
Date: 2018-12-23, YearWeek: 201851
Date: 2018-12-24, YearWeek: 201851
Date: 2018-12-25, YearWeek: 201851
Date: 2018-12-26, YearWeek: 201851
Date: 2018-12-27, YearWeek: 201851
Date: 2018-12-28, YearWeek: 201852
Date: 2018-12-29, YearWeek: 201852
Date: 2018-12-30, YearWeek: 201852
Date: 2018-12-31, YearWeek: 201852
Date: 2019-01-01, YearWeek: 201852
Date: 2019-01-02, YearWeek: 201852
Date: 2019-01-03, YearWeek: 201852
Date: 2019-01-04, YearWeek: 201901
Date: 2019-01-05, YearWeek: 201901
Date: 2019-01-06, YearWeek: 201901
Date: 2019-01-07, YearWeek: 201901
Date: 2019-01-08, YearWeek: 201901
Date: 2019-01-09, YearWeek: 201901
Date: 2019-01-10, YearWeek: 201901
Date: 2019-01-11, YearWeek: 201902
Upvotes: 0
Reputation: 24028
Kinda hacky, but this will do the job:
import datetime
def week(t):
if datetime.datetime(t.year, 1, 1).weekday() == 6:
# The year started with a Sunday.
incr = 0
else:
incr = 1
return int(t.strftime("%U")) + incr
ls = [datetime.datetime(2019, 1, 5), datetime.datetime(2019, 1, 6),
datetime.datetime(2019, 8, 3), datetime.datetime(2019, 8, 4),
datetime.datetime(2017, 1, 1)]
for t in ls:
print("day:", t.strftime("%Y-%m-%d %a,"), "week:", week(t))
Output:
day: 2019-01-05 Sat, week: 1 day: 2019-01-06 Sun, week: 2 day: 2019-08-03 Sat, week: 31 day: 2019-08-04 Sun, week: 32 day: 2017-01-01 Sun, week: 1
Upvotes: 6