码迷,mamicode.com
首页 > 编程语言 > 详细

Python3 输入日期显示星期几

时间:2020-03-25 21:48:12      阅读:283      评论:0      收藏:0      [点我收藏+]

标签:初始   print   try   星期几   code   计算   参数错误   python3   while   

 

import time
import traceback
def findLen(str):
    counter = 0
    while str[counter:]:
        counter += 1
    return counter
def is_valid_date(str_date):
    ‘‘‘判断是否是一个有效的日期字符串‘‘‘
    try:
        time.strptime(str_date, "%Y%m%d")
        return True
    except Exception:
        # traceback.print_exc()
        raise Exception("时间参数错误 near : {}".format(str_date))

#print("20180101是星期一,作为参考日期")
#jisuan_riqi = input("请输入你要计算的日期(20180101):")
year=eval(input("请输入年:"))
month=eval(input("请输入月:"))
day=eval(input("请输入日:"))
jisuan_riqi=str(year)+str(month)+str(day)
jisuan=str(year)+/+str(month)+/+str(day)
if(is_valid_date(jisuan_riqi)):
#平年每月天数
    month_list1 = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
#闰年每月天数
    month_list2 = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

# 输入的年份大于等于2018年
    if year >= 2018:
        year_days = 0
        for i in range(2018, year):
        # 先做出一个判断,判断年份是否是闰年
            if (i % 4 == 0 & (i % 100 != 0)) | (i % 400 == 0):
                year_days += 366#闰年
            else:
                year_days += 365#平年
        month_days = 0
        day_days=0
        if ((year % 4 == 0) & (year % 100 != 0)) | (year % 400 == 0):
            for j in range(month - 1):
                month_days += month_list2[j]
        else:
            for j in range(month - 1):
                month_days += month_list1[j]

        total_days = year_days + month_days + day

    # 相差天数与7取余,+1表明余数为0是周一
        xingqi = (total_days - 1) % 7 + 1
        print("你输入的日期 %s" % jisuan_riqi, "是周", xingqi)

# 输入的年份小于2018年
    else:
    # 计算2018年之前的日期时,先将2018的一天作为初始,加入到总天数中
        year_days = 1
        for i in range(2017, year, -1):
            # 先做出一个判断,判断年份是否是闰年,在对其进行天数的计算
            if (i % 4 == 0 & (i % 100 != 0)) | (i % 400 == 0):
                year_days += 366
            else:
                year_days += 365
        month_days = 0
        if (year % 4 == 0 & (year % 100 != 0)) | (year % 400 == 0):
            for j in range(11, month - 2, -1):
                month_days += month_list2[j]
        else:
            for j in range(11, month - 1, -1):
                month_days += month_list1[j]
        total_days = year_days + month_days - day
        if (total_days) % 7 == 0:
            xingqi = (total_days) % 7 + 1
        else:
            # 余数为1是周7,余数为2是周6,所以8-余数
            xingqi = 8 - (total_days) % 7
        print("你输入的日期 %s" % jisuan_riqi, "是周", xingqi)

 

Python3 输入日期显示星期几

标签:初始   print   try   星期几   code   计算   参数错误   python3   while   

原文地址:https://www.cnblogs.com/zmh-980509/p/12569310.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!