"""
作者:Troublemaker
功能:判断第几天
版本:1.0+2.0
日期:2019/10/7 9:25
脚本:1.0.py
新增:用tuple替换list
"""
import datetime
import math
def main():
"""
主函数
"""
input_date_str = input("请输入日期:(格式:xxxx/xx/xx)")
get_date = datetime.datetime.strptime(input_date_str, '%Y/%m/%d')
# 非闰年列表
month_list = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
# 非闰年元组
month_tuple = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
# 得到年,月,日
which_year = get_date.year
which_month = get_date.month
which_day = get_date.day
# 计算非闰年的总天数
# total_day = math.fsum(month_list[:(which_month - 1)]) + which_day
total_day = math.fsum(month_tuple[:(which_month - 1)]) + which_day
# 判断是否是闰年
if (which_year % 400 == 0) or ((which_year % 100 != 0) and (which_year % 4 == 0)):
if which_month >= 3: # 如果闰年月份在三月以后的才能加1
total_day += 1
print("这是{}年的第{}天。".format(which_year, total_day))
if __name__ == '__main__':
main()
"""
作者:Troublemaker
功能:判断第几天
版本:3.0
日期:2019/10/7 10:28
脚本:3.0.py
新增:将月份划分为不同的集合再操作
"""
import datetime
def main():
"""
主函数
"""
input_date_str = input("请输入日期:(格式:xxxx/xx/xx)")
get_date = datetime.datetime.strptime(input_date_str, '%Y/%m/%d')
# 31天的集合
_31day_set = {1, 3, 5, 7, 8, 10, 12}
# 30天的集合
_30day_set = {4, 6, 9, 11}
# 得到年,月,日
which_year = get_date.year
which_month = get_date.month
which_day = get_date.day
# 计算非闰年的总天数
total_day = 0
total_day += which_day
for month in range(1, which_month):
if month in _31day_set:
total_day += 31
elif month in _30day_set:
total_day += 30
else:
total_day += 28
# 判断是否是闰年
if (which_year % 400 == 0) or ((which_year % 100 != 0) and (which_year % 4 == 0)):
if which_month >= 3: # 如果闰年月份在三月以后的才能加1
total_day += 1
print("这是{}年的第{}天。".format(which_year, total_day))
if __name__ == '__main__':
main()
字典(dict)
字典的一些操作
字典的遍历
遍历所有key
for key in dict.keys():
print(key)
遍历所有vlaue
for value in dict.values():
print(value)
遍历所有key和对应的value,即所有数据项
for item in dict.items():
print(item)
"""
作者:Troublemaker
功能:判断第几天
版本:4.0
日期:2019/10/7 11:01
脚本:4.0.py
新增:将月份及其对应天数通过字典表示
"""
import datetime
def main():
"""
主函数
"""
input_date_str = input("请输入日期:(格式:xxxx/xx/xx)")
get_date = datetime.datetime.strptime(input_date_str, '%Y/%m/%d')
# 月份的字典
month_dict = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31}
# 得到年,月,日
which_year = get_date.year
which_month = get_date.month
which_day = get_date.day
# 计算非闰年的总天数
total_day = 0
total_day += which_day
for month in range(1, which_month):
total_day += month_dict[month]
# 判断是否是闰年
if (which_year % 400 == 0) or ((which_year % 100 != 0) and (which_year % 4 == 0)):
if which_month >= 3: # 如果闰年月份在三月以后的才能加1
total_day += 1
print("这是{}年的第{}天。".format(which_year, total_day))
if __name__ == '__main__':
main()
"""
作者:Troublemaker
功能:一行代码得到一年中的第几天
版本:
日期:2019/10/7 19:41
脚本:one_code.py
"""
import time
def main():
input_date_str = input("请输入日期:(格式:xxxx/xx/xx)")
which_day = time.strptime(input_date_str, "%Y/%m/%d")
print(which_day.tm_yday)
if __name__ == '__main__':
main()