python获取本年度每月第一天,每月最后一天,时间-1天,日期分季度

获取本年度每月第一天,每月最后一天

# -*- coding: utf-8 -*-
"""
Date:2021
"""
import time
import datetime
import calendar

class DateUtils:
    """DateUtils"""
    def __init__(self):

    def getStartDate(self):
        """开始时间"""
        year = datetime.datetime.now().year
        d = []
        for num in range(1, 13):
            temp = ""
            if num < 10:
                temp = str(year) + '-0' + str(num) + "-01"
            else:
                temp = str(year) + '-' + str(num) + "-01"
            d.append(temp)
        return d

    def getEndDate(self):
        """结束时间"""
        year = datetime.datetime.now().year
        d = []
        for num in range(1, 13):
            # 获取当前月的第一天的星期和当月总天数
            weekDay, monthCountDay = calendar.monthrange(year, num)
            d.append(str(datetime.date(year, num, day=monthCountDay)))
        return d
        
if __name__ == '__main__':
    d = DateUtils()
   	print(d.getStartDate())
    print(d.getEndDate())
输出结果:
['2022-01-01', '2022-02-01', '2022-03-01', '2022-04-01', '2022-05-01', '2022-06-01', '2022-07-01', '2022-08-01', '2022-09-01', '2022-10-01', '2022-11-01', '2022-12-01']
['2022-01-31', '2022-02-28', '2022-03-31', '2022-04-30', '2022-05-31', '2022-06-30', '2022-07-31', '2022-08-31', '2022-09-30', '2022-10-31', '2022-11-30', '2022-12-31']

文章借鉴:https://cloud.tencent.com/developer/article/1073164
文章借鉴:https://www.cnblogs.com/test-hui/p/12067671.html
文章借鉴:https://www.cnblogs.com/aixiao07/p/13489159.html

时间-1天

    year = datetime.datetime.now().year
    dd = str(year) + '-03-01'
    re_date = (datetime.datetime.strptime(dd, '%Y-%m-%d').date() - datetime.timedelta(days=1)).strftime('%Y-%m-%d')

日期分季度

    def getBetweenQuarter(self, value):
        if 'CST' in value:
            value = self.trans_format(value, '%a %b %d %H:%M:%S CST %Y', '%Y-%m-%d %H:%M:%S')
        temp_value = value.split("-")
        if temp_value[1] in ['01', '02', '03']:
            return "Q1"
        elif temp_value[1] in ['04', '05', '06']:
            return "Q2"
        elif temp_value[1] in ['07', '08', '09']:
            return "Q3"
        elif temp_value[1] in ['10', '11', '12']:
            return "Q4"

    def trans_format(self, time_string, from_format, to_format='%Y.%m.%d %H:%M:%S'):
        time_struct = time.strptime(time_string, from_format)
        times = time.strftime(to_format, time_struct)
        return times

你可能感兴趣的:(Python,python,开发语言,后端)