如何计算Python中两个日期之间一年中的天数 [英] How to Calculate the number of days in the year(s) between 2 dates in python

查看:456
本文介绍了如何计算Python中两个日期之间一年中的天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

date 1 : 1 january 2000  
date 2 : 17 november 2006  

我想知道2000、2001年的日期1和日期2之间有多少天... ,2006
,所以我需要返回类似这样的内容(无论是否在列表中或其他内容):

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

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,尝试如下操作:

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.

编辑:更正range()调用的边界,正确处理year1 == year2

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

这篇关于如何计算Python中两个日期之间一年中的天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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