python求下一个月的今天

https://docs.python.org/3/library/calendar.html?highlight=calendar#calendar.monthrange


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 datetime. datetime ( year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0 )

The year, month and day arguments are required. tzinfo may be None, or aninstance of a tzinfo 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.


#引入日历

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值