How to get the last day of the month?

后端 未结 30 2500
迷失自我
迷失自我 2020-11-22 06:13

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

If the standard library doesn\'t support

相关标签:
30条回答
  • 2020-11-22 06:50

    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)
    
    0 讨论(0)
  • 2020-11-22 06:51
    from datetime import timedelta
    (any_day.replace(day=1) + timedelta(days=32)).replace(day=1) - timedelta(days=1)
    
    0 讨论(0)
  • 2020-11-22 06:51

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

    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.

    0 讨论(0)
  • 2020-11-22 06:52

    This is the simplest solution for me using just the standard datetime library:

    import datetime
    
    def get_month_end(dt):
        first_of_month = datetime.datetime(dt.year, dt.month, 1)
        next_month_date = first_of_month + datetime.timedelta(days=32)
        new_dt = datetime.datetime(next_month_date.year, next_month_date.month, 1)
        return new_dt - datetime.timedelta(days=1)
    
    0 讨论(0)
  • 2020-11-22 06:53
    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)
    
    0 讨论(0)
  • 2020-11-22 06:54

    The easiest & most reliable way I've found so Far is as:

    from datetime import datetime
    import calendar
    days_in_month = calendar.monthrange(2020, 12)[1]
    end_dt = datetime(2020, 12, days_in_month)
    
    0 讨论(0)
提交回复
热议问题