简体   繁体   中英

Counting the number of days in a range by month in Python?

I am trying to count the number of days in a range of dates by month. So let's say a range of dates occurs between 2 months since the beginning and ending dates are in 2 different months. I want the output to show that x amount of days in the range fall in one month and x amount of days fall in the next month.

So far my code only outputs each day in the range from 10 days after veterans day (my start date) to 20 days after veterans day (end date):

import datetime

Veterans = datetime.datetime(2019, 11, 12)

print(Veterans)
number_of_days = 10
ten_days = datetime.timedelta(days=10)
vetplus10 = Veterans + ten_days

date_list = [(vetplus10 + datetime.timedelta(days=day)).isoformat() for day in range(number_of_days)]

print(date_list)

['2019-11-22T00:00:00', '2019-11-23T00:00:00', '2019-11-24T00:00:00', '2019-11-25T00:00:00', '2019-11-26T00:00:00', '2019-11-27T00:00:00', '2019-11-28T00:00:00', '2019-11-29T00:00:00', '2019-11-30T00:00:00', '2019-12-01T00:00:00']

The idea here would be for python to tally up all the days in November (9) and all the days in December (1). Thank you in advance!

You can try using pandas to create a date range, convert it to a month and get the value counts.

import pandas as pd

pd.date_range(start='2019-11-22', periods=10, freq='D').to_period('M').value_counts()

2019-11    9
2019-12    1

I was able to get similar output without using an additional library:

import datetime

Veterans = datetime.datetime(2019, 11, 12)

print(Veterans)
number_of_days = 10
ten_days = datetime.timedelta(days=10)
vetplus10 = Veterans + ten_days

date_list = [(vetplus10 + datetime.timedelta(days=day)) for day in range(number_of_days)]

day_counts = {}
for day in date_list:
    day_counts[f"{day.year}-{day.month}"] = day_counts.get(f"{day.year}-{day.month}", 0) + 1

print(day_counts)

2019-11-12 00:00:00

{'2019-11': 9, '2019-12': 1}

Essentially, I simply iterate over the datetime objects in your original list, and build a dictionary for each year-month that it encounters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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