calendar.
monthrange
(year, month)
-
Returns weekday of first day of the month and number of days in month, for thespecified year and month.
https://docs.python.org/3/library/datetime.html#datetime.datetime
Constructor:
-
class
-
The year, month and day arguments are required. tzinfo may be
None
, or aninstance of atzinfo
subclass. The remaining arguments may be integers,in the following ranges:MINYEAR <= year <= MAXYEAR
,1 <= month <= 12
,1 <= day <= number of days in the given month and year
,0 <= hour < 24
,0 <= minute < 60
,0 <= second < 60
,0 <= microsecond < 1000000
,fold in [0, 1]
.
If an argument outside those ranges is given,
ValueError
is raised.New in version 3.6: Added the
fold
argument.
datetime.
datetime
(
year,
month,
day,
hour=0,
minute=0,
second=0,
microsecond=0,
tzinfo=None,
*,
fold=0
)
#引入日历
import calendar
#参数是(哪年,哪月),datetime.now().year表示今年,datetime.now().month表示当月
calendar.monthrange(datetime.now().year, datetime.now().month)
#返回值是元组,第一个数6表示当月第一天的星期(0
is Monday, 6
is Sunday),第二个数30表示这个月有30天
(6, 30)
再用当前时间加上时间间隔(当月的天数):
days_num = calendar.monthrange(datetime.now().year, datetime.now().month)[1]
from datetime import timedelta
today_of_next_month = datetime.now() + timedelta(days = days_num)
如果求上个月的今天不能这么算,因为需要减去上个月的天数,上个月是几月不确定,只能求出这个月的第一天,减一天,得到上个月的最后一天。
# 取本月的第一天
first_day = datetime(datetime.now().year, datetime.now().month, 1)
first_day
打印结果:
datetime.datetime(2018, 4, 1, 0, 0)
# 本月第一天再减一天为上月的最后一天
first_day - timedelta(days = 1)
打印结果:
datetime.datetime(2018, 3, 31, 0, 0)
pre_month_last_day = first_day - timedelta(days = 1)
pre_month_last_day
打印结果:
datetime.datetime(2018, 3, 31, 0, 0)
#取上月最后一天的月份
pre_month_last_day.month
打印结果:
3
# 最后通过上月最后一天的年,上月最后一天的月,和今天的天,生成上月的今天
datetime(pre_month_last_day.year, pre_month_last_day.month, datetime.now().day)
打印结果:
datetime.datetime(2018, 3, 19, 0, 0)
# 求上一个月的今天,输入输出格式datetime.datetime(2018, 3, 19, 0, 0) def todayoflastmonth(dt): # 本月第一天 firstday = datetime(dt.year, dt.month, 1) # 上月最后一天 premonthlastday = firstday - timedelta(days=1) # 返回上月的今天 return datetime(premonthlastday.year, premonthlastday.month, dt.day)
参考:https://blog.csdn.net/xiao_huocai/article/details/75571138