python 时间操作

2022-09-07 11:32:33 浏览数 (1)

function 1 ,获取指定年份间隔 以每月划分的月list

代码语言:javascript复制
import copy
import calendar
from dateutil.relativedelta import relativedelta


def get_time_list():
    time_create = '2018-10-01 00:00:00'  # TODO
    time_distance = '2018-10-31 23:59:59'  # TODO
    time_end = '2019-08-31 23:59:59'
    start = datetime.datetime.strptime(time_create, "%Y-%m-%d %H:%M:%S")
    delatime = datetime.datetime.strptime(time_distance, "%Y-%m-%d %H:%M:%S")
    end_time = datetime.datetime.strptime(time_end, "%Y-%m-%d %H:%M:%S")
    time_list = [[start, delatime]]
    while start < end_time:
        start  = relativedelta(months=1)
        delatime  = relativedelta(months=1)
        end = start   datetime.timedelta(days=calendar.monthrange(start.year, start.month)[1] - 1, hours=23, minutes=59,seconds=59)
        end = copy.deepcopy(end)
        time_list.append([start, end])
    res = time_list[:-2]
    # print(res)
    return res

function 2 ,获取指定月份 以每周划分的周list

代码语言:javascript复制
def get_week_time_list(start, end):
    week_time = list()
    temp = start
    for _ in range(4):
        start  = datetime.timedelta(days=7)
        if (end - start).days < 5:
            start = end
        week_time.append([temp, start])
        temp = start
    # print(week_time)
    return week_time

0 人点赞