Receive month after week, day and year

I want to know how you get months by date, week number and year.

For example, if you have something like this

def getmonth(day, week, year): # by day, week and year calculate the month print (month) getmonth(28, 52, 2014) # print 12 getmonth(13, 42, 2014) # print 10 getmonth(6, 2, 2015) # print 1 
+6
source share
4 answers

Per suggestion interjay :

 import datetime as DT def getmonth(day, week, year): for month in range(1, 13): try: date = DT.datetime(year, month, day) except ValueError: continue iso_year, iso_weeknum, iso_weekday = date.isocalendar() if iso_weeknum == week: return date.month print(getmonth(28, 52, 2014)) # 12 print(getmonth(13, 42, 2014)) # 10 print(getmonth(6, 2, 2015)) # 1 
+2
source
 from datetime import datetime, timedelta def getmonth(day, week, year): d = datetime.strptime('%s %s 1' % (week-1, year), '%W %Y %w') for i in range(0, 7): d2 = d + timedelta(days=i) if d2.day == day: return d2.month 
+2
source

You can do this with isoweek , something like this for your first example:

 from isoweek import Week w = Week(2014, 52) candidates = [date for date in w.days() if date.day == 28] assert len(candidates) == 1 date = candidates[0] # your answer 
+2
source

I use python-dateutil when I need to perform some complicated date operations.

 from datetime import date from dateutil.rrule import YEARLY, rrule def get_month(day, week, year): rule = rrule(YEARLY, byweekno=week, bymonthday=day, dtstart=date(year, 1, 1)) return rule[0].month 
+2
source

Source: https://habr.com/ru/post/980226/


All Articles