一周一天,一天一年

Sig*_*ils 6 python python-3.x

我想知道你如何通过给予日,周数和年份来获得月份.

例如,如果你有这样的东西

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
Run Code Online (Sandbox Code Playgroud)

unu*_*tbu 2

根据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
Run Code Online (Sandbox Code Playgroud)