Python -- 生成一年中的每天

离线断网项目需要获取一年当中每天

代码:

# !/usr/bin/python3
# -*- coding=utf-8 -*-
# @Author  : zunsi
# @file: getalldayperyear.py
# @time: 2021-01-11  18:32:20


import arrow


def isLeapYear(years):
    '''
    通过判断闰年,获取年份years下一年的总天数
    :param years: 年份,int
    :return:days_sum,一年的总天数
    '''
    # 断言:年份不为整数时,抛出异常。
    assert isinstance(years, int), "请输入整数年,如 2018"

    if ((years % 4 == 0 and years % 100 != 0) or (years % 400 == 0)):  # 判断是否是闰年
        # print(years, "是闰年")
        days_sum = 366
        return days_sum
    else:
        # print(years, '不是闰年')
        days_sum = 365
        return days_sum


def getAllDayPerYear(years):
    '''
    获取一年的所有日期
    :param years:年份
    :return:全部日期列表
    '''
    start_date = '%s-1-1' % years
    a = 0
    all_date_list = []
    days_sum = isLeapYear(int(years))
    print()
    while a < days_sum:
        b = arrow.get(start_date).shift(days=a).format("YYYY-MM-DD")
        a += 1
        all_date_list.append(b)
    # print(all_date_list)
    return all_date_list


if __name__ == '__main__':
    # years = "2001"
    # years = int(years)
    # # 通过判断闰年,获取一年的总天数
    # days_sum = isLeapYear(years)

    # 获取一年的所有日期
    # all_date_list = getAllDayPerYear("2022")
    # print(all_date_list)
    # print(len(all_date_list))

日期时间格式化(补0):

import time

ti = time.localtime()
ti_1 = ('0'+str(ti[1])) if ti[1] < 10 else ti[1]  # 月份补0
ti_2 = ('0'+str(ti[2])) if ti[2] < 10 else ti[2]  # 日期补0
ti_4 = ('0'+str(ti[4])) if ti[4] < 10 else ti[4]   # 分钟补0
t = "%s-%s-%s" % (ti[0], ti_1, ti_2)  #  格式: 2021-1-1 改为 2021-01-01
h = "%s:%s" % (ti[3], ti_4) # 生成当前的时间 18:5 修改该为18:05

结果:

posted @   kleinscnb  阅读(5)  评论(0编辑  收藏  举报  
点击右上角即可分享
微信分享提示