pandas 在python中检查是否是月底

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31753384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:42:44  来源:igfitidea点击:

Check if it is the end of the month in python

pythondatetimepandas

提问by jenryb

I am writing code to take data from the last year. I want to round up the earlier date like so: If it is July 14 2015, I want data from August 1st 2014-July 14,2015

我正在编写代码来获取去年的数据。我想像这样对较早的日期进行四舍五入:如果是 2015 年 7 月 14 日,我想要 2014 年 8 月 1 日至 2015 年 7 月 14 日的数据

df = pd.read_csv('MyData.csv') 
df['recvd_dttm'] = pd.to_datetime(df['recvd_dttm'])
range_max = datetime.datetime.now() 
range_min = range_max - pd.tseries.offsets.DateOffset(years=1)+ pd.tseries.offsets.MonthEnd(1) + pd.tseries.offsets.DateOffset(days=1)
if datetime.datetime.now() == is_month_end:

# take slice with final week of data
df = df[(df['recvd_dttm'] >= range_min) & 
               (df['recvd_dttm'] <= range_max)]

My problem is that when it is July 31, 2015, my code goes to the end of the nextmonth, essentially cutting out an entire month.

我的问题是,当它是2015年7月31日,我的代码转到结束未来一个月,基本上切割出一整月。

I am trying to make a for loop to fix this problem.

我正在尝试制作一个 for 循环来解决这个问题。

If it is the end of the month:

如果是月底:

range_min = range_max - pd.tseries.offsets.DateOffset(years=1)

else:

别的:

range_min = range_max - pd.tseries.offsets.DateOffset(years=1)+ pd.tseries.offsets.MonthEnd(1) + pd.tseries.offsets.DateOffset(days=1)

How do I tell python to check for the end of the month? MonthEnd is only an offset function.

我如何告诉python检查月底?MonthEnd 只是一个偏移函数。

采纳答案by jenryb

Alright, here's what I did. Found the calendar module that BryanOakley suggested and made this loop. It checks the current day and checks if it is the same as the last day of the month, and chooses the range_min accordingly.

好的,这就是我所做的。找到了 BryanOakley 建议的日历模块并制作了这个循环。它检查当前日期并检查它是否与该月的最后一天相同,并相应地选择 range_min。

if datetime.datetime.now().day == calendar.monthrange(date.year, date.month)[1]:
    range_min = range_max - pd.tseries.offsets.DateOffset(years=1)+ pd.tseries.offsets.DateOffset(days=1)
else:
    range_min = range_max - pd.tseries.offsets.DateOffset(years=1)+ pd.tseries.offsets.MonthEnd(1) + pd.tseries.offsets.DateOffset(days=1)

回答by Marco Di Cesare

I simply would use the monthrange method of calendar module to find last day number of the month:

我只是使用日历模块的 monthrange 方法来查找该月的最后一天:

    def check_if_last_day_of_week(date):
        import datetime
        import calendar
        #  calendar.monthrange return a tuple (weekday of first day of the 
        #  month, number  
        #  of days in month)
        last_day_of_month = calendar.monthrange(date.year, date.month)[1]
        # here i check if date is last day of month
        if date == datetime.date(date.year, date.month, last_day_of_month):
            return True
        return False


>>> date = datetime.date(2018, 12, 31)
>>> check_if_last_day_of_week(date)
True

回答by Alexander

This method is relatively simple and does not require any modules.

这种方法比较简单,不需要任何模块。

today = datetime.date.today()  # 2015-07-31
prior_month = 1 if today.month is 12 else today.month + 1
prior_year = today.year if today.month is 12 else today.year - 1

>>> datetime.date(prior_year, prior_month, 1)
datetime.date(2014, 8, 1)

回答by Andy

Here is a short function to accomplish this. It requires the dateutilmodule so that you can do relative date math.

这是完成此操作的简短函数。它需要dateutil模块,以便您可以进行相对日期数学运算。

import datetime
from dateutil.relativedelta import relativedelta

def lastyear_period_start(current_date):
    last_year = current_date - relativedelta(months=11)
    return datetime.date(last_year.year, last_year.month, 1)

It can be utilized like so:

它可以像这样使用:

dates = [
    datetime.datetime(2010, 2, 27),
    datetime.datetime(2011, 2, 27),
    datetime.datetime(2012, 2, 27),
    datetime.datetime(2013, 2, 27),
    datetime.datetime(2014, 2, 27),
    datetime.datetime(2010, 7, 27),
    datetime.datetime(2011, 7, 27),
    datetime.datetime(2012, 7, 27),
    datetime.datetime(2013, 7, 27),
    datetime.datetime(2014, 7, 27),
    datetime.datetime(2015, 7, 14),
    datetime.datetime(2015, 7, 31),
    datetime.datetime(2011, 2, 28),
    datetime.datetime(2012, 2, 29),
    datetime.datetime(2013, 2, 28),
]

for d in dates:
    print d, lastyear_period_start(d)

This prints that following

这会打印以下内容

2010-02-27 00:00:00 2009-03-01
2011-02-27 00:00:00 2010-03-01
2012-02-27 00:00:00 2011-03-01
2013-02-27 00:00:00 2012-03-01
2014-02-27 00:00:00 2013-03-01
2010-07-27 00:00:00 2009-08-01
2011-07-27 00:00:00 2010-08-01
2012-07-27 00:00:00 2011-08-01
2013-07-27 00:00:00 2012-08-01
2014-07-27 00:00:00 2013-08-01
2015-07-14 00:00:00 2014-08-01
2015-07-31 00:00:00 2014-08-01
2011-02-28 00:00:00 2010-03-01
2012-02-29 00:00:00 2011-03-01
2013-02-28 00:00:00 2012-03-01


In the function we're doing two simple steps

在函数中我们做了两个简单的步骤

  • last_year = current_date - relativedelta(months=11)
  • last_year = current_date - relativedelta(months=11)

First we find out what the date was 11 months ago, based on the date passed to the function

首先,我们根据传递给函数的日期找出 11 个月前的日期

  • return datetime.date(last_year.year, last_year.month, 1)
  • return datetime.date(last_year.year, last_year.month, 1)

Then we return the first day of that month.

然后我们返回那个月的第一天。

In the output above you can see this accounts for leap years as well.

在上面的输出中,您也可以看到这对闰年的解释。