1
是否有一種特殊的方法來派生這個或我們必須創建循環?這個函數的參數實際上是(year,num_of_days)。但我不知道如何從中獲得數月。 這是我到目前爲止(不完整),但它沒有考慮到不同月份的日子。有沒有更簡單的方法來解決這個問題?提前致謝!如何在Python3中使用datetime將日期轉換爲月份?
def daynum_to_date(year : int, daynum : int) -> datetime.date:
'''Return the date corresponding to the year and the day number, daynum,
within the year.
Hint: datetime handles leap years for you, so don't think about them.
Examples:
>>> daynum_to_date(2011, 1) # first day of the year
datetime.date(2011, 1, 1)
>>> daynum_to_date(2011, 70)
datetime.date(2011, 3, 11)
>>> daynum_to_date(2012, 70)
datetime.date(2012, 3, 10)
'''
import calendar
totalmonths = 0
i = 1
while i < 13:
month_days = calendar.monthrange(year,i)[1]
months = daynum//int(month_days)
if months in range(2):
days = daynum % int(month_days)
totalmonths = totalmonths + 1
else:
daynum = daynum - int(month_days)
totalmonths = totalmonths + 1
i = i + 1
return datetime.date(year, totalmonths, days)