python输入日期计算天数_如何计算Python中两个日期之间一年中的天数

For example:

date 1 : 1 january 2000

date 2 : 17 november 2006

I want to know how many days there are between date 1 and date 2 in the year 2000, 2001, ..., 2006

so I need something that returns something like this (doesn't matter if it's in a list or something):

2000: 365, 2001: 365, ..., 2006: 320

I've looked for something like this on the internet but that only turned up ways to calculate the number of days/months/years between 2 dates

解决方案

hm, try something like this:

import datetime, calendar

date1 = datetime.date(year1, month1, day1) # month and day are 1-base

date2 = datetime.date(year2, month2, day2)

days_in_first_year = (datetime.date(year1,12,31)-date1).days

days_in_last_year = (date2 - datetime.date(year2, 1, 1)).days

if year1 != year2:

n_days_list = [days_in_first_year]

for year in range(year1+1, year2): n_days_list.append(365 + (1*calendar.isleap(year)))

n_days_list.append(days_in_last_year)

else: n_days_list = [days_in_first_year + days_in_last_year]

haven't tested this, might be some off-by-one errors; make sure it does what you expect.

edit: correct the boundaries of the range() call, correctly handle year1 == year2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值