转自:http://www.weidianyuedu.com/content/3713893637927.html
- 获取本周/本月/上月最后一天
本周
代码如下:
import datetime
today = datetime.date.today()
today
datetime.date(2016, 11, 26)sunday = today + datetime.timedelta(6 - today.weekday())
sunday
datetime.date(2016, 11, 27)
本月
代码如下:
import calendar
today = datetime.date.today()
_, last_day_num = calendar.monthrange(today.year, today.month)
last_day = datetime.date(today.year, today.month, last_day_num)
last_day
datetime.date(2016, 11, 30)
获取上个月的最后一天(可能跨年)
代码如下:
import datetime
today = datetime.date.today()
first = datetime.date(day=1, month=today.month, year=today.year)
lastMonth = first - datetime.timedelta(days=1)
lastMonth
datetime.date(2016, 10, 31)
其他使用例子:
#当月1号 datetime.date(datetime.date.today().year,datetime.date.today().month,1)
#当月1号 datetime.date.today().replace(day=1)
#上月1号 (datetime.date.today().replace(day=1) - datetime.timedelta(1)).replace(day=1)