检查它是否是python中的月末

时间:2015-07-31 19:04:14

标签: python datetime pandas

我正在编写代码来获取去年的数据。我想像这样整理早期日期:如果是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)]

我的问题是,当它是2015年7月31日时,我的代码将在 next 月结束,基本上会缩短整个月。

我正在尝试使用for循环来解决此问题。

如果是月末:

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

否则:

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

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

7 个答案:

答案 0 :(得分:0)

我只是使用日历模块的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

答案 1 :(得分:0)

我们可以避免导入带有仅利用calendar的简短功能的datetime模块。

如果明天的月份与今天的月份不同,则表示今天是当前月份的最后一天。我们可以通过短函数(例如

)以编程方式进行检查
import datetime 
def end_of_month(dt):
    todays_month = dt.month
    tomorrows_month = (dt + datetime.timedelta(days=1)).month
    return True if tomorrows_month != todays_month else False

现在,针对您的特定用例:

now = datetime.datetime.now()
if end_of_month(now):
    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)

答案 2 :(得分:0)

import datetime
def find_curr_month_end_date(curr_date):
    if(curr_date.month != 12):
        next_month_first_date= curr_date.replace(day=1).replace(month=curr_date.month+1)
    else:
        next_month_first_date= curr_date.replace(day=1).replace(month=1).replace(year=curr_date.year+1)

    curr_month_end_date = next_month_first_date - datetime.timedelta(days=1)

    return curr_month_end_date


curr_date = datetime.datetime.today() 
# or curr_date = datetime.datetime.strptime("2020-12-16","%Y-%m-%d")
curr_month_end_date = 
find_curr_month_end_date(curr_date)

答案 3 :(得分:0)

我使用的是 Pandas,我不想包含另一个库,所以我用它来检查是否是一个月的最后一天和一年的最后一天:

import pandas as pd

my_date = '31-12-2021'

current_data = pd.to_datetime(my_date, format='%d-%m-%Y')
current_month = current_data.month
current_year = current_data.year

following_day = current_data + pd.DateOffset(1)
tomorrows_month = following_day.month
tomorrows_year = following_day.year

is_last_day_of_month = True if tomorrows_month != current_month else False
is_last_day_of_year = True if tomorrows_year != current_year else False

答案 4 :(得分:-1)

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

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)

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

  • 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.

答案 5 :(得分:-1)

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.

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)

答案 6 :(得分:-1)

此方法相对简单,不需要任何模块。

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)