我想知道你如何按照给定日,周数和年份来获得月份。
例如,如果你有这样的东西
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
答案 0 :(得分:2)
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
答案 1 :(得分:2)
您可以使用isoweek模块执行此操作,例如第一个示例:
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 :(得分:2)
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
答案 3 :(得分:2)
当我需要实施一些棘手的日期操作时,我正在使用python-dateutil。
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