使用Python获取每个月的最后一天

时间:2022-10-16 12:06:02

Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?

是否有一种方法可以使用Python的标准库轻松地确定(即一个函数调用)给定月份的最后一天?

If the standard library doesn't support that, does the dateutil package support this?

如果标准库不支持这个,dateutil包是否支持这个?

24 个解决方案

#1


789  

I didn't notice this earlier when I was looking at the documentation for the calendar module, but a method called monthrange provides this information:

我之前在查看日历模块的文档时没有注意到这一点,但是monthrange方法提供了以下信息:

monthrange(year, month)
    Returns weekday of first day of the month and number of days in month, for the specified year and month.

monthrange(年、月)返回每月第一天的工作日和每月的天数,用于指定的年和月。

>>> import calendar
>>> calendar.monthrange(2002,1)
(1, 31)
>>> calendar.monthrange(2008,2)
(4, 29)
>>> calendar.monthrange(2100,2)
(0, 28)

so:

所以:

calendar.monthrange(year, month)[1]

seems like the simplest way to go.

这似乎是最简单的方法。

Just to be clear, monthrange supports leap years as well:

明确地说,monthrange也支持闰年:

>>> from calendar import monthrange
>>> monthrange(2012, 2)
(2, 29)

My previous answer still works, but is clearly suboptimal.

我之前的答案仍然有效,但显然不是最佳答案。

#2


88  

If you don't want to import the calendar module, a simple two-step function can also be:

如果您不想导入日历模块,简单的两步函数也可以是:

import datetime

def last_day_of_month(any_day):
    next_month = any_day.replace(day=28) + datetime.timedelta(days=4)  # this will never fail
    return next_month - datetime.timedelta(days=next_month.day)

Outputs:

输出:

>>> for month in range(1, 13):
...     print last_day_of_month(datetime.date(2012, month, 1))
...
2012-01-31
2012-02-29
2012-03-31
2012-04-30
2012-05-31
2012-06-30
2012-07-31
2012-08-31
2012-09-30
2012-10-31
2012-11-30
2012-12-31

#3


59  

EDIT: See @Blair Conrad's answer for a cleaner solution

编辑:参见@Blair Conrad的“更干净的解决方案”


>>> import datetime
>>> datetime.date (2000, 2, 1) - datetime.timedelta (days = 1)
datetime.date(2000, 1, 31)
>>> 

#4


37  

EDIT: see my other answer. It has a better implementation than this one, which I leave here just in case someone's interested in seeing how one might "roll your own" calculator.

编辑:看我的另一个答案。它有一个比这个更好的实现,我离开这里只是为了以防万一有人对如何“滚你自己的”计算器感兴趣。

@John Millikin gives a good answer, with the added complication of calculating the first day of the next month.

@John Millikin给出了一个很好的答案,并增加了计算下个月的第一天的复杂性。

The following isn't particularly elegant, but to figure out the last day of the month that any given date lives in, you could try:

下面的例子不是特别优雅,但要算出每个特定日期的最后一天,你可以试试:

def last_day_of_month(date):
    if date.month == 12:
        return date.replace(day=31)
    return date.replace(month=date.month+1, day=1) - datetime.timedelta(days=1)

>>> last_day_of_month(datetime.date(2002, 1, 17))
datetime.date(2002, 1, 31)
>>> last_day_of_month(datetime.date(2002, 12, 9))
datetime.date(2002, 12, 31)
>>> last_day_of_month(datetime.date(2008, 2, 14))
datetime.date(2008, 2, 29)

#5


27  

This is actually pretty easy with dateutil.relativedelta (package python-datetutil for pip). day=31 will always always return the last day of the month.

使用dateutil时,这实际上非常简单。相对论三角洲(为pip包python-datetutil)。天=31总是会返回一个月的最后一天。

Example:

例子:

from datetime import datetime
from dateutil.relativedelta import relativedelta

date_in_feb = datetime.datetime(2013, 2, 21)
print datetime.datetime(2013, 2, 21) + relativedelta(day=31)  # End-of-month
>>> datetime.datetime(2013, 2, 28, 0, 0)

#6


12  

Using relativedelta you would get last date of month like this:

使用相对论三角洲你会得到这样的最后一个月的日期:

from dateutil.relativedelta import relativedelta
last_date_of_month = datetime(mydate.year,mydate.month,1)+relativedelta(months=1,days=-1)

The idea is to get the fist day of month and use relativedelta to go 1 month ahead and 1 day back so you would get the last day of the month you wanted.

我们的想法是在每个月的第一天用相对论delta来提前1个月,然后再提前1天,这样你就能得到你想要的最后一天。

#7


11  

Another solution would be to do something like this:

另一种解决办法是这样做:

from datetime import datetime

def last_day_of_month(year, month):
    """ Work out the last day of the month """
    last_days = [31, 30, 29, 28, 27]
    for i in last_days:
        try:
            end = datetime(year, month, i)
        except ValueError:
            continue
        else:
            return end.date()
    return None

And use the function like this:

使用如下函数:

>>> 
>>> last_day_of_month(2008, 2)
datetime.date(2008, 2, 29)
>>> last_day_of_month(2009, 2)
datetime.date(2009, 2, 28)
>>> last_day_of_month(2008, 11)
datetime.date(2008, 11, 30)
>>> last_day_of_month(2008, 12)
datetime.date(2008, 12, 31)

#8


9  

from datetime import timedelta
(any_day.replace(day=1) + timedelta(days=32)).replace(day=1) - timedelta(days=1)

#9


7  

>>> import datetime
>>> import calendar
>>> date  = datetime.datetime.now()

>>> print date
2015-03-06 01:25:14.939574

>>> print date.replace(day = 1)
2015-03-01 01:25:14.939574

>>> print date.replace(day = calendar.monthrange(date.year, date.month)[1])
2015-03-31 01:25:14.939574

#10


5  

import datetime

now = datetime.datetime.now()
start_month = datetime.datetime(now.year, now.month, 1)
date_on_next_month = start_month + datetime.timedelta(35)
start_next_month = datetime.datetime(date_on_next_month.year, date_on_next_month.month, 1)
last_day_month = start_next_month - datetime.timedelta(1)

#11


5  

if you are willing to use an external library, check out http://crsmithdev.com/arrow/

如果您愿意使用外部库,请查看http://crsmithdev.com/arrow/

U can then get the last day of the month with:

然后你可以用:

import arrow
arrow.utcnow().ceil('month').date()

This returns a date object which you can then do your manipulation.

它返回一个日期对象,您可以对其进行操作。

#12


3  

For me it's the simplest way:

对我来说,这是最简单的方式:

selected_date = date(some_year, some_month, some_day)

if selected_date.month == 12: # December
     last_day_selected_month = date(selected_date.year, selected_date.month, 31)
else:
     last_day_selected_month = date(selected_date.year, selected_date.month + 1, 1) - timedelta(days=1)

#13


3  

To get the last date of the month we do something like this:

为了得到这个月的最后一个日期,我们做了如下的事情:

from datetime import date, timedelta
import calendar
last_day = date.today().replace(day=calendar.monthrange(date.today().year, date.today().month)[1])

Now to explain what we are doing here we will break it into two parts:

现在来解释一下我们在这里做什么我们将把它分成两部分:

first is getting the number of days of the current month for which we use monthrange which Blair Conrad has already mentioned his solution:

首先是得到这个月的天数我们用的是monthrange布莱尔·康拉德已经提到过他的解决方案:

calendar.monthrange(date.today().year, date.today().month)[1]

second is getting the last date itself which we do with the help of replace e.g

第二是得到最后一次约会,我们用替换来做

>>> date.today()
datetime.date(2017, 1, 3)
>>> date.today().replace(day=31)
datetime.date(2017, 1, 31)

and when we combine them as mentioned on the top we get a dynamic solution.

当我们把它们结合到上面时,我们得到了一个动态解。

#14


3  

The easiest way (without having to import calendar), is to get the first day of the next month, and then subtract a day from it.

最简单的方法(不需要导入日历)是获得下个月的第一天,然后减去一天。

import datetime as dt
from dateutil.relativedelta import relativedelta

thisDate = dt.datetime(2017, 11, 17)

last_day_of_the_month = dt.datetime(thisDate.year, (thisDate + relativedelta(months=1)).month, 1) - dt.timedelta(days=1)
print last_day_of_the_month

Output:

输出:

datetime.datetime(2017, 11, 30, 0, 0)

PS: This code runs faster as compared to the import calendarapproach; see below:

PS:与导入日历方法相比,该代码运行速度更快;见下文:

import datetime as dt
import calendar
from dateutil.relativedelta import relativedelta

someDates = [dt.datetime.today() - dt.timedelta(days=x) for x in range(0, 10000)]

start1 = dt.datetime.now()
for thisDate in someDates:
    lastDay = dt.datetime(thisDate.year, (thisDate + relativedelta(months=1)).month, 1) - dt.timedelta(days=1)

print ('Time Spent= ', dt.datetime.now() - start1)


start2 = dt.datetime.now()
for thisDate in someDates:
    lastDay = dt.datetime(thisDate.year, 
                          thisDate.month, 
                          calendar.monthrange(thisDate.year, thisDate.month)[1])

print ('Time Spent= ', dt.datetime.now() - start2)

OUTPUT:

输出:

Time Spent=  0:00:00.097814
Time Spent=  0:00:00.109791

This code assumes that you want the date of the last day of the month (i.e., not just the DD part, but the entire YYYYMMDD date)

这段代码假设您想要一个月的最后一天的日期(例如。,不只是DD部分,而是整个YYYYMMDD日期)

#15


1  

This does not address the main question, but one nice trick to get the last weekday in a month is to use calendar.monthcalendar, which returns a matrix of dates, organized with Monday as the first column through Sunday as the last.

这并没有解决主要问题,但是一个很好的方法是在一个月的最后一个工作日使用日历。月历,返回一个日期矩阵,周一作为第一列,周日作为最后一列。

# Some random date.
some_date = datetime.date(2012, 5, 23)

# Get last weekday
last_weekday = np.asarray(calendar.monthcalendar(some_date.year, some_date.month))[:,0:-2].ravel().max()

print last_weekday
31

The whole [0:-2] thing is to shave off the weekend columns and throw them out. Dates that fall outside of the month are indicated by 0, so the max effectively ignores them.

整件事[0:-2]就是砍掉周末专栏,把它们扔出去。月外的日期用0表示,因此max实际上忽略了它们。

The use of numpy.ravel is not strictly necessary, but I hate relying on the mere convention that numpy.ndarray.max will flatten the array if not told which axis to calculate over.

numpy的使用。拉威尔并不是绝对必要的,但我讨厌仅仅依赖于numpi .ndarray这个约定。如果不告诉max要计算哪个轴,max会把数组弄平。

#16


1  

Use pandas!

用熊猫!

def isMonthEnd(date):
    return date + pd.offsets.MonthEnd(0) == date

isMonthEnd(datetime(1999, 12, 31))
True
isMonthEnd(pd.Timestamp('1999-12-31'))
True
isMonthEnd(pd.Timestamp(1965, 1, 10))
False

#17


1  

I prefer this way

我更喜欢这种方式

import datetime
import calendar

date=datetime.datetime.now()
month_end_date=datetime.datetime(date.year,date.month,1) + datetime.timedelta(days=calendar.monthrange(date.year,date.month)[1] - 1)

#18


1  

You can calculate the end date yourself. the simple logic is to subtract a day from the start_date of next month. :)

你可以自己计算结束日期。简单的逻辑是从下个月的start_date中减去一天。:)

So write a custom method,

写一个自定义方法,

import datetime

def end_date_of_a_month(date):


    start_date_of_this_month = date.replace(day=1)

    month = start_date_of_this_month.month
    year = start_date_of_this_month.year
    if month == 12:
        month = 1
        year += 1
    else:
        month += 1
    next_month_start_date = start_date_of_this_month.replace(month=month, year=year)

    this_month_end_date = next_month_start_date - datetime.timedelta(days=1)
    return this_month_end_date

Calling,

打电话,

end_date_of_a_month(datetime.datetime.now().date())

It will return the end date of this month. Pass any date to this function. returns you the end date of that month.

它将返回本月的结束日期。将任何日期传递给这个函数。返回你的月底的日期。

#19


0  

import calendar
from time import gmtime, strftime
calendar.monthrange(int(strftime("%Y", gmtime())), int(strftime("%m", gmtime())))[1]

Output:

输出:

31



This will print the last day of whatever the current month is. In this example it was 15th May, 2016. So your output may be different, however the output will be as many days that the current month is. Great if you want to check the last day of the month by running a daily cron job.

这将打印出当前月份的最后一天。在这个例子中是2016年5月15日。所以你的输出可能是不同的,但是输出会和当前月一样多。如果你想通过每天做cron工作来检查一个月的最后一天,那就太棒了。

So:

所以:

import calendar
from time import gmtime, strftime
lastDay = calendar.monthrange(int(strftime("%Y", gmtime())), int(strftime("%m", gmtime())))[1]
today = strftime("%d", gmtime())
lastDay == today

Output:

输出:

False

Unless it IS the last day of the month.

除非是这个月的最后一天。

#20


0  

If you want to make your own small function, this is a good starting point:

如果你想做自己的小函数,这是一个很好的起点:

def eomday(year, month):
    """returns the number of days in a given month"""
    days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    d = days_per_month[month - 1]
    if month == 2 and (year % 4 == 0 and year % 100 != 0 or year % 400 == 0):
        d = 29
    return d

For this you have to know the rules for the leap years:

为此,你必须知道闰年的规则:

  • every fourth year
  • 每四年
  • with the exception of every 100 year
  • 除了每100年
  • but again every 400 years
  • 但每400年一次

#21


0  

If you pass in a date range, you can use this:

如果你通过一个日期范围,你可以使用这个:

def last_day_of_month(any_days):
    res = []
    for any_day in any_days:
        nday = any_day.days_in_month -any_day.day
        res.append(any_day + timedelta(days=nday))
    return res

#22


0  

Here is a solution based python lambdas:

下面是一个基于python lambdas的解决方案:

next_month = lambda y, m, d: (y, m + 1, 1) if m + 1 < 13 else ( y+1 , 1, 1)
month_end  = lambda dte: date( *next_month( *dte.timetuple()[:3] ) ) - timedelta(days=1)

The next_month lambda finds the tuple representation of the first day of the next month, and rolls over to the next year. The month_end lambda transforms a date (dte) to a tuple, applies next_month and creates a new date. Then the "month's end" is just the next month's first day minus timedelta(days=1).

next_month lambda发现下个月的第一天的元组表示,并一直延续到下一年。month_end lambda将日期(dte)转换为元组,应用next_month并创建一个新的日期。那么“月末”就是下个月的第一天减去时间增量(天数=1)。

#23


-2  

I hope,It's usefull for very much..Try it on this way..we must need import some package

我希望这对你有帮助。试试这种方法。我们必须进口一些包装

import time
from datetime import datetime, date
from datetime import timedelta
from dateutil import relativedelta

  start_date = fields.Date(
        string='Start Date', 
        required=True,
        ) 

    end_date = fields.Date(
        string='End Date', 
        required=True,
        )

    _defaults = {
        'start_date': lambda *a: time.strftime('%Y-%m-01'),
        'end_date': lambda *a: str(datetime.now() + relativedelta.relativedelta(months=+1, day=1, days=-1))[:10],
    }

#24


-6  

i have a simple solution:

我有一个简单的解决办法:

import datetime   
datetime.date(2012,2, 1).replace(day=1,month=datetime.date(2012,2,1).month+1)-timedelta(days=1)
datetime.date(2012, 2, 29)

#1


789  

I didn't notice this earlier when I was looking at the documentation for the calendar module, but a method called monthrange provides this information:

我之前在查看日历模块的文档时没有注意到这一点,但是monthrange方法提供了以下信息:

monthrange(year, month)
    Returns weekday of first day of the month and number of days in month, for the specified year and month.

monthrange(年、月)返回每月第一天的工作日和每月的天数,用于指定的年和月。

>>> import calendar
>>> calendar.monthrange(2002,1)
(1, 31)
>>> calendar.monthrange(2008,2)
(4, 29)
>>> calendar.monthrange(2100,2)
(0, 28)

so:

所以:

calendar.monthrange(year, month)[1]

seems like the simplest way to go.

这似乎是最简单的方法。

Just to be clear, monthrange supports leap years as well:

明确地说,monthrange也支持闰年:

>>> from calendar import monthrange
>>> monthrange(2012, 2)
(2, 29)

My previous answer still works, but is clearly suboptimal.

我之前的答案仍然有效,但显然不是最佳答案。

#2


88  

If you don't want to import the calendar module, a simple two-step function can also be:

如果您不想导入日历模块,简单的两步函数也可以是:

import datetime

def last_day_of_month(any_day):
    next_month = any_day.replace(day=28) + datetime.timedelta(days=4)  # this will never fail
    return next_month - datetime.timedelta(days=next_month.day)

Outputs:

输出:

>>> for month in range(1, 13):
...     print last_day_of_month(datetime.date(2012, month, 1))
...
2012-01-31
2012-02-29
2012-03-31
2012-04-30
2012-05-31
2012-06-30
2012-07-31
2012-08-31
2012-09-30
2012-10-31
2012-11-30
2012-12-31

#3


59  

EDIT: See @Blair Conrad's answer for a cleaner solution

编辑:参见@Blair Conrad的“更干净的解决方案”


>>> import datetime
>>> datetime.date (2000, 2, 1) - datetime.timedelta (days = 1)
datetime.date(2000, 1, 31)
>>> 

#4


37  

EDIT: see my other answer. It has a better implementation than this one, which I leave here just in case someone's interested in seeing how one might "roll your own" calculator.

编辑:看我的另一个答案。它有一个比这个更好的实现,我离开这里只是为了以防万一有人对如何“滚你自己的”计算器感兴趣。

@John Millikin gives a good answer, with the added complication of calculating the first day of the next month.

@John Millikin给出了一个很好的答案,并增加了计算下个月的第一天的复杂性。

The following isn't particularly elegant, but to figure out the last day of the month that any given date lives in, you could try:

下面的例子不是特别优雅,但要算出每个特定日期的最后一天,你可以试试:

def last_day_of_month(date):
    if date.month == 12:
        return date.replace(day=31)
    return date.replace(month=date.month+1, day=1) - datetime.timedelta(days=1)

>>> last_day_of_month(datetime.date(2002, 1, 17))
datetime.date(2002, 1, 31)
>>> last_day_of_month(datetime.date(2002, 12, 9))
datetime.date(2002, 12, 31)
>>> last_day_of_month(datetime.date(2008, 2, 14))
datetime.date(2008, 2, 29)

#5


27  

This is actually pretty easy with dateutil.relativedelta (package python-datetutil for pip). day=31 will always always return the last day of the month.

使用dateutil时,这实际上非常简单。相对论三角洲(为pip包python-datetutil)。天=31总是会返回一个月的最后一天。

Example:

例子:

from datetime import datetime
from dateutil.relativedelta import relativedelta

date_in_feb = datetime.datetime(2013, 2, 21)
print datetime.datetime(2013, 2, 21) + relativedelta(day=31)  # End-of-month
>>> datetime.datetime(2013, 2, 28, 0, 0)

#6


12  

Using relativedelta you would get last date of month like this:

使用相对论三角洲你会得到这样的最后一个月的日期:

from dateutil.relativedelta import relativedelta
last_date_of_month = datetime(mydate.year,mydate.month,1)+relativedelta(months=1,days=-1)

The idea is to get the fist day of month and use relativedelta to go 1 month ahead and 1 day back so you would get the last day of the month you wanted.

我们的想法是在每个月的第一天用相对论delta来提前1个月,然后再提前1天,这样你就能得到你想要的最后一天。

#7


11  

Another solution would be to do something like this:

另一种解决办法是这样做:

from datetime import datetime

def last_day_of_month(year, month):
    """ Work out the last day of the month """
    last_days = [31, 30, 29, 28, 27]
    for i in last_days:
        try:
            end = datetime(year, month, i)
        except ValueError:
            continue
        else:
            return end.date()
    return None

And use the function like this:

使用如下函数:

>>> 
>>> last_day_of_month(2008, 2)
datetime.date(2008, 2, 29)
>>> last_day_of_month(2009, 2)
datetime.date(2009, 2, 28)
>>> last_day_of_month(2008, 11)
datetime.date(2008, 11, 30)
>>> last_day_of_month(2008, 12)
datetime.date(2008, 12, 31)

#8


9  

from datetime import timedelta
(any_day.replace(day=1) + timedelta(days=32)).replace(day=1) - timedelta(days=1)

#9


7  

>>> import datetime
>>> import calendar
>>> date  = datetime.datetime.now()

>>> print date
2015-03-06 01:25:14.939574

>>> print date.replace(day = 1)
2015-03-01 01:25:14.939574

>>> print date.replace(day = calendar.monthrange(date.year, date.month)[1])
2015-03-31 01:25:14.939574

#10


5  

import datetime

now = datetime.datetime.now()
start_month = datetime.datetime(now.year, now.month, 1)
date_on_next_month = start_month + datetime.timedelta(35)
start_next_month = datetime.datetime(date_on_next_month.year, date_on_next_month.month, 1)
last_day_month = start_next_month - datetime.timedelta(1)

#11


5  

if you are willing to use an external library, check out http://crsmithdev.com/arrow/

如果您愿意使用外部库,请查看http://crsmithdev.com/arrow/

U can then get the last day of the month with:

然后你可以用:

import arrow
arrow.utcnow().ceil('month').date()

This returns a date object which you can then do your manipulation.

它返回一个日期对象,您可以对其进行操作。

#12


3  

For me it's the simplest way:

对我来说,这是最简单的方式:

selected_date = date(some_year, some_month, some_day)

if selected_date.month == 12: # December
     last_day_selected_month = date(selected_date.year, selected_date.month, 31)
else:
     last_day_selected_month = date(selected_date.year, selected_date.month + 1, 1) - timedelta(days=1)

#13


3  

To get the last date of the month we do something like this:

为了得到这个月的最后一个日期,我们做了如下的事情:

from datetime import date, timedelta
import calendar
last_day = date.today().replace(day=calendar.monthrange(date.today().year, date.today().month)[1])

Now to explain what we are doing here we will break it into two parts:

现在来解释一下我们在这里做什么我们将把它分成两部分:

first is getting the number of days of the current month for which we use monthrange which Blair Conrad has already mentioned his solution:

首先是得到这个月的天数我们用的是monthrange布莱尔·康拉德已经提到过他的解决方案:

calendar.monthrange(date.today().year, date.today().month)[1]

second is getting the last date itself which we do with the help of replace e.g

第二是得到最后一次约会,我们用替换来做

>>> date.today()
datetime.date(2017, 1, 3)
>>> date.today().replace(day=31)
datetime.date(2017, 1, 31)

and when we combine them as mentioned on the top we get a dynamic solution.

当我们把它们结合到上面时,我们得到了一个动态解。

#14


3  

The easiest way (without having to import calendar), is to get the first day of the next month, and then subtract a day from it.

最简单的方法(不需要导入日历)是获得下个月的第一天,然后减去一天。

import datetime as dt
from dateutil.relativedelta import relativedelta

thisDate = dt.datetime(2017, 11, 17)

last_day_of_the_month = dt.datetime(thisDate.year, (thisDate + relativedelta(months=1)).month, 1) - dt.timedelta(days=1)
print last_day_of_the_month

Output:

输出:

datetime.datetime(2017, 11, 30, 0, 0)

PS: This code runs faster as compared to the import calendarapproach; see below:

PS:与导入日历方法相比,该代码运行速度更快;见下文:

import datetime as dt
import calendar
from dateutil.relativedelta import relativedelta

someDates = [dt.datetime.today() - dt.timedelta(days=x) for x in range(0, 10000)]

start1 = dt.datetime.now()
for thisDate in someDates:
    lastDay = dt.datetime(thisDate.year, (thisDate + relativedelta(months=1)).month, 1) - dt.timedelta(days=1)

print ('Time Spent= ', dt.datetime.now() - start1)


start2 = dt.datetime.now()
for thisDate in someDates:
    lastDay = dt.datetime(thisDate.year, 
                          thisDate.month, 
                          calendar.monthrange(thisDate.year, thisDate.month)[1])

print ('Time Spent= ', dt.datetime.now() - start2)

OUTPUT:

输出:

Time Spent=  0:00:00.097814
Time Spent=  0:00:00.109791

This code assumes that you want the date of the last day of the month (i.e., not just the DD part, but the entire YYYYMMDD date)

这段代码假设您想要一个月的最后一天的日期(例如。,不只是DD部分,而是整个YYYYMMDD日期)

#15


1  

This does not address the main question, but one nice trick to get the last weekday in a month is to use calendar.monthcalendar, which returns a matrix of dates, organized with Monday as the first column through Sunday as the last.

这并没有解决主要问题,但是一个很好的方法是在一个月的最后一个工作日使用日历。月历,返回一个日期矩阵,周一作为第一列,周日作为最后一列。

# Some random date.
some_date = datetime.date(2012, 5, 23)

# Get last weekday
last_weekday = np.asarray(calendar.monthcalendar(some_date.year, some_date.month))[:,0:-2].ravel().max()

print last_weekday
31

The whole [0:-2] thing is to shave off the weekend columns and throw them out. Dates that fall outside of the month are indicated by 0, so the max effectively ignores them.

整件事[0:-2]就是砍掉周末专栏,把它们扔出去。月外的日期用0表示,因此max实际上忽略了它们。

The use of numpy.ravel is not strictly necessary, but I hate relying on the mere convention that numpy.ndarray.max will flatten the array if not told which axis to calculate over.

numpy的使用。拉威尔并不是绝对必要的,但我讨厌仅仅依赖于numpi .ndarray这个约定。如果不告诉max要计算哪个轴,max会把数组弄平。

#16


1  

Use pandas!

用熊猫!

def isMonthEnd(date):
    return date + pd.offsets.MonthEnd(0) == date

isMonthEnd(datetime(1999, 12, 31))
True
isMonthEnd(pd.Timestamp('1999-12-31'))
True
isMonthEnd(pd.Timestamp(1965, 1, 10))
False

#17


1  

I prefer this way

我更喜欢这种方式

import datetime
import calendar

date=datetime.datetime.now()
month_end_date=datetime.datetime(date.year,date.month,1) + datetime.timedelta(days=calendar.monthrange(date.year,date.month)[1] - 1)

#18


1  

You can calculate the end date yourself. the simple logic is to subtract a day from the start_date of next month. :)

你可以自己计算结束日期。简单的逻辑是从下个月的start_date中减去一天。:)

So write a custom method,

写一个自定义方法,

import datetime

def end_date_of_a_month(date):


    start_date_of_this_month = date.replace(day=1)

    month = start_date_of_this_month.month
    year = start_date_of_this_month.year
    if month == 12:
        month = 1
        year += 1
    else:
        month += 1
    next_month_start_date = start_date_of_this_month.replace(month=month, year=year)

    this_month_end_date = next_month_start_date - datetime.timedelta(days=1)
    return this_month_end_date

Calling,

打电话,

end_date_of_a_month(datetime.datetime.now().date())

It will return the end date of this month. Pass any date to this function. returns you the end date of that month.

它将返回本月的结束日期。将任何日期传递给这个函数。返回你的月底的日期。

#19


0  

import calendar
from time import gmtime, strftime
calendar.monthrange(int(strftime("%Y", gmtime())), int(strftime("%m", gmtime())))[1]

Output:

输出:

31



This will print the last day of whatever the current month is. In this example it was 15th May, 2016. So your output may be different, however the output will be as many days that the current month is. Great if you want to check the last day of the month by running a daily cron job.

这将打印出当前月份的最后一天。在这个例子中是2016年5月15日。所以你的输出可能是不同的,但是输出会和当前月一样多。如果你想通过每天做cron工作来检查一个月的最后一天,那就太棒了。

So:

所以:

import calendar
from time import gmtime, strftime
lastDay = calendar.monthrange(int(strftime("%Y", gmtime())), int(strftime("%m", gmtime())))[1]
today = strftime("%d", gmtime())
lastDay == today

Output:

输出:

False

Unless it IS the last day of the month.

除非是这个月的最后一天。

#20


0  

If you want to make your own small function, this is a good starting point:

如果你想做自己的小函数,这是一个很好的起点:

def eomday(year, month):
    """returns the number of days in a given month"""
    days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    d = days_per_month[month - 1]
    if month == 2 and (year % 4 == 0 and year % 100 != 0 or year % 400 == 0):
        d = 29
    return d

For this you have to know the rules for the leap years:

为此,你必须知道闰年的规则:

  • every fourth year
  • 每四年
  • with the exception of every 100 year
  • 除了每100年
  • but again every 400 years
  • 但每400年一次

#21


0  

If you pass in a date range, you can use this:

如果你通过一个日期范围,你可以使用这个:

def last_day_of_month(any_days):
    res = []
    for any_day in any_days:
        nday = any_day.days_in_month -any_day.day
        res.append(any_day + timedelta(days=nday))
    return res

#22


0  

Here is a solution based python lambdas:

下面是一个基于python lambdas的解决方案:

next_month = lambda y, m, d: (y, m + 1, 1) if m + 1 < 13 else ( y+1 , 1, 1)
month_end  = lambda dte: date( *next_month( *dte.timetuple()[:3] ) ) - timedelta(days=1)

The next_month lambda finds the tuple representation of the first day of the next month, and rolls over to the next year. The month_end lambda transforms a date (dte) to a tuple, applies next_month and creates a new date. Then the "month's end" is just the next month's first day minus timedelta(days=1).

next_month lambda发现下个月的第一天的元组表示,并一直延续到下一年。month_end lambda将日期(dte)转换为元组,应用next_month并创建一个新的日期。那么“月末”就是下个月的第一天减去时间增量(天数=1)。

#23


-2  

I hope,It's usefull for very much..Try it on this way..we must need import some package

我希望这对你有帮助。试试这种方法。我们必须进口一些包装

import time
from datetime import datetime, date
from datetime import timedelta
from dateutil import relativedelta

  start_date = fields.Date(
        string='Start Date', 
        required=True,
        ) 

    end_date = fields.Date(
        string='End Date', 
        required=True,
        )

    _defaults = {
        'start_date': lambda *a: time.strftime('%Y-%m-01'),
        'end_date': lambda *a: str(datetime.now() + relativedelta.relativedelta(months=+1, day=1, days=-1))[:10],
    }

#24


-6  

i have a simple solution:

我有一个简单的解决办法:

import datetime   
datetime.date(2012,2, 1).replace(day=1,month=datetime.date(2012,2,1).month+1)-timedelta(days=1)
datetime.date(2012, 2, 29)