python3 datetime,如何使用Python3中的datetime将日期转换成几个月?

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)

解决方案

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 "", line 1, in

File "", 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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值