zoukankan      html  css  js  c++  java
  • 计算从今天起上一个月的日期

     1 from datetime import *
     2 import calendar
     3 
     4 def get_monthago_date():
     5     nowtime = date.today()
     6     nowtime_year = nowtime.year
     7     nowtime_month = nowtime.month
     8     nowtime_day = nowtime.day
     9     
    10     onemonthago = nowtime_month - 1    #减去一个月,判断是否为0,为0表示当前月份是1月份
    11     
    12     if onemonthago == 0:    #如果当前月份为1月份,就需要设置年份减去1,月份为12月
    13         oneyearago = nowtime_year - 1
    14         onemonthago = 12
    15         monthindex, monthdays = calendar.monthrange(oneyearago, onemonthago)    #获取上一个月有多少天
    16         
    17         if monthdays >= nowtime_day:    #如果上一个月的总天数大于当前日期就用当前的日期
    18             onemonthdate = nowtime.replace(year=oneyearago, month=onemonthago, day=nowtime_day)
    19         else:    #如果上一个月的总天数都小于当前的日期(2月28和3.31这种情况)就使用上个月的最大日期
    20             onemonthdate = nowtime.replace(year=oneyearago, month=onemonthago, day=monthdays)
    21             
    22         return onemonthdate.strftime('%Y-%m-%d')
    23     else:
    24         monthindex, monthdays = calendar.monthrange(nowtime_year, onemonthago)
    25         
    26         if monthdays >= nowtime_day:
    27             onemonthdate = nowtime.replace(year=nowtime_year, month=onemonthago, day=nowtime_day)
    28         else:
    29             onemonthdate = nowtime.replace(year=nowtime_year, month=onemonthago, day=monthdays)
    30             
    31         return onemonthdate.strftime('%Y-%m-%d')
  • 相关阅读:
    接口测试工具postman学习
    接口测试工具jmeter压力测试
    WSGI规范
    ADB命令详解
    eclipse导入远端git
    os.system、os.popen和subprocess.popen的区别
    获取Android当前运行最顶层的activity
    python+appuim 处理系统权限弹窗
    Appium之xpath定位元素
    Charles配置抓取HTTPS请求的Android配置
  • 原文地址:https://www.cnblogs.com/hushaojun/p/4729420.html
Copyright © 2011-2022 走看看