【问题标题】:How to convert days into months using datetime in Python3?如何在 Python3 中使用 datetime 将天数转换为月数?
【发布时间】:2013-03-05 14:26:37
【问题描述】:

有没有一种特殊的方法来推导出这个,还是我们必须创建循环?这个函数的参数实际上是(year, num_of_days)。但我不知道如何从中得出几个月。 这是我到目前为止所拥有的(不完整),但它没有考虑到不同的月份。有没有更简单的方法来解决这个问题?提前致谢!

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)

【问题讨论】:

    标签: python datetime python-3.3


    【解决方案1】:

    你快到了:

    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))
    

    给出:

    >>> 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)
    

    【讨论】:

      猜你喜欢
      • 2013-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-30
      • 1970-01-01
      • 2022-06-10
      相关资源
      最近更新 更多