如何使用Python3中的datetime将日期转换成几个月? [英] How to convert days into months using datetime in Python3?

查看:658
本文介绍了如何使用Python3中的datetime将日期转换成几个月?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a special method to derive this or do we have to create loops? The parameters for this function is actually (year, num_of_days). But I have no idea how to derive months from this. This is what I have so far (incomplete) but it doesn't take into the different month days into account. Is there an easier way to tackle this question? Thanks in advance!

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)


推荐答案

你几乎在那里:

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)

这篇关于如何使用Python3中的datetime将日期转换成几个月?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆