Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get month by week, day and year

I want to know how you get the months by the giving day, 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
like image 411
Sigils Avatar asked Dec 28 '14 09:12

Sigils


1 Answers

Per interjay's suggestion:

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
like image 162
unutbu Avatar answered Nov 05 '22 15:11

unutbu