Python程序来查找月份的最后日期
给定一个 datetime 对象,任务是编写一个Python程序来计算 datetime 对象 Month 的最后一个日期。
例子:
Input : test_date = datetime.datetime(2018, 6, 4)
Output : 30
Explanation : April has 30 days, each year
Input : test_date = datetime.datetime(2020, 2, 4)
Output : 29
Explanation : February had 29 days in 2020, leap year.
方法#1:使用replace() + timedelta()
在此,提取下个月,减去从下个月提取的下个月对象的日期,得到下个月开始前1天,即当月的最后日期。
Python3
# Python3 code to demonstrate working of
# Get Last date of Month
# Using replace() + timedelta()
import datetime
# initializing date
test_date = datetime.datetime(2018, 6, 4)
# printing original date
print("The original date is : " + str(test_date))
# getting next month
# using replace to get to last day + offset
# to reach next month
nxt_mnth = test_date.replace(day=28) + datetime.timedelta(days=4)
# subtracting the days from next month date to
# get last date of current Month
res = nxt_mnth - datetime.timedelta(days=nxt_mnth.day)
# printing result
print("Last date of month : " + str(res.day))
Python3
# Python3 code to demonstrate working of
# Get Last date of Month
# Using calendar()
from datetime import datetime
import calendar
# initializing date
test_date = datetime(2018, 6, 4)
# printing original date
print("The original date is : " + str(test_date))
# monthrange() gets the date range
# required of month
res = calendar.monthrange(test_date.year, test_date.month)[1]
# printing result
print("Last date of month : " + str(res))
输出:
The original date is : 2018-06-04 00:00:00
Last date of month : 30
方法#2:使用 calendar()
这使用内置函数来解决这个问题。在此,给定年份和月份,可以使用 monthrange() 计算范围,其第二个元素可以获得所需的结果。
蟒蛇3
# Python3 code to demonstrate working of
# Get Last date of Month
# Using calendar()
from datetime import datetime
import calendar
# initializing date
test_date = datetime(2018, 6, 4)
# printing original date
print("The original date is : " + str(test_date))
# monthrange() gets the date range
# required of month
res = calendar.monthrange(test_date.year, test_date.month)[1]
# printing result
print("Last date of month : " + str(res))
输出:
The original date is : 2018-06-04 00:00:00
Last date of month : 30