简体   繁体   English

计算两个日期之间的月数(python)

[英]Calculate days in months between 2 dates (python)

I have a table with events and for each event there is a start date and end date, I need to get the amount of days each event had in different months.我有一个事件表,每个事件都有一个开始日期和结束日期,我需要获取每个事件在不同月份的天数。

For example:例如:

Event 1 Start date: 1.1.2021 End date: 4.3.2021活动 1 开始日期:1.1.2021 结束日期:4.3.2021

January 2021: 31 days February 2021: 28 days March 2021: 4 days 2021 年 1 月:31 天 2021 年 2 月:28 天 2021 年 3 月:4 天

Anyway to do this using pandas/python library?无论如何要使用pandas/python库来做到这一点?

The piece of code below prints the days contained in each month between the dates d0 and d1 .下面的一段代码打印日期d0d1之间每个月包含的天数。

It prints the days between d0 and end of d0 months.它打印d0d0月结束之间的天数。 It then prints the days in each of the following months until it reaches d1 month.然后打印接下来每个月的天数,直到到达d1个月。 At that point, it just prints the day of the d1 date.那时,它只打印d1日期的那一天。

In this case, datetime and dateutil.relativedelta are used to handle datetime objects and month increases.在这种情况下, datetimedateutil.relativedelta用于处理日期时间对象和月份增加。

from datetime import date
from dateutil.relativedelta import *

d0 = date(2008, 8, 18)
d1 = date(2009, 9, 26)

def days_in_month(month, year):
    if month == 12:
        return (date(year+1, 1, 1) - date(year, month, 1)).days
    return (date(year, month+1, 1) - date(year, month, 1)).days

def get_month_year_string(date):
    return date.strftime("%B %Y")

d = d0
while d.month < d1.month or d.year < d1.year:
    days_to_end_month = days_in_month(d.month, d.year)
    if d == d0:
        days_to_end_month -= d0.day
    print(f'{get_month_year_string(d)}: {days_to_end_month} days')
    d = d + relativedelta(months=+1)
print(f'{get_month_year_string(d1)}: {d1.day} days')

# Output:
# August 2008: 13 days
# September 2008: 30 days
# October 2008: 31 days
# November 2008: 30 days
# December 2008: 31 days
# January 2009: 31 days
# February 2009: 28 days
# March 2009: 31 days
# April 2009: 30 days
# May 2009: 31 days
# June 2009: 30 days
# July 2009: 31 days
# August 2009: 31 days
# September 2009: 26 days

Using pandas , you could follow this approach:使用pandas ,您可以遵循以下方法:

import pandas as pd
import datetime as dt

# YOUR INPUTS
start_date = dt.datetime(2020, 1, 1)
end_date = dt.datetime(2020, 4, 4)

# All the days between start_date and end_date
days = pd.date_range(start_date, end_date)
# Retrieve first day for each of the month within the range
d = {x.strftime("%Y%m"):x for x in sorted(days, reverse=True)}
# Append end_date
d = [*sorted(d.values()), end_date]

for d1, d2 in zip(d[:-1], d[1:]):
    n_days = (d2 - d1).days + (d1.month == d2.month)
    print("{:15s}:{:d}".format(d1.strftime("%B %Y"), n_days))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM