我有一個事件表,每個事件都有一個開始日期和結束日期,我需要獲取每個事件在不同月份的天數。
例如:
活動 1 開始日期:1.1.2021 結束日期:4.3.2021
2021 年 1 月:31 天 2021 年 2 月:28 天 2021 年 3 月:4 天
無論如何要使用pandas/python庫來做到這一點?
uj5u.com熱心網友回復:
下面的一段代碼列印每個月中包含的日期d0和日期之間的天數d1。
它列印d0月末和月末之間的天d0數。然后列印接下來d1每個月的天數,直到到達月份。那時,它只列印日期的那d1一天。
在這種情況下,datetime和dateutil.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
uj5u.com熱心網友回復:
使用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))
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/334596.html
上一篇:使用另一列連接多列并避免空白值
