How to convert days into months using datetime in Python3?

吃可爱长大的小学妹 提交于 2019-12-06 14:36:31

You are nearly there:

import calendar
import datetime

def daynum_to_date(year : int, daynum : int) -> datetime.date:
    month = 1
    day = daynum
    while month < 13:
        month_days = calendar.monthrange(year, month)[1]
        if day <= month_days:
            return datetime.date(year, month, day)
        day -= month_days
        month += 1
    raise ValueError('{} does not have {} days'.format(year, daynum))

which gives:

>>> daynum_to_date(2012, 366)
datetime.date(2012, 12, 31)
>>> daynum_to_date(2012, 367)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 10, in daynum_to_date
ValueError: 2012 does not have 367 days
>>> daynum_to_date(2012, 70)
datetime.date(2012, 3, 10)
>>> daynum_to_date(2011, 70)
datetime.date(2011, 3, 11)
>>> daynum_to_date(2012, 1)
datetime.date(2012, 1, 1)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!