PYTHON:根据出生年月日计算年龄并且分段(datatime空间里的datatime模块)

实验内容​ 

  1. 从网站下载python语言的开发环境,并安装。
  2. 设计一个数据结构存储全校学生的基本情况。
  3. 基本情况应该包括:学号,姓名(可能存在同名),性别,年龄
  4. 设计程序实现通过姓名查找学生。
  5. 可以统计每个年龄段的人数。

思路

       创建一个字典作为数据库, 一个键值对多个键值储存多个学生的信息。通过for循环匹配要查找的姓名与学生的姓名是否相同,是的话就输出用户指定的信息。判断学生的年龄是否处于指定的年龄段,是的话就使数组对应元素计数加一。

程序源代码

import datetime
people = {
'1235':{
    'name':'Alice',
    'sex':'girl',
    'age':'2012-09-15'
    },
'1234':{
    'name':'Alice',
    'sex':'girl',
    'age':'1997-11-08'
    },
'5628':{
    'name':'Beth',
    'sex':'boy',
    'age':'1882-03-03'
     },
'5728':{
    'name':'Beth',
    'sex':'boy',
    'age':'1990-01-05'
     },
'4785':{
    'name':'Cecil',
    'sex':'girl',
    'age':'2015-03-10'
     }
}

labels = {
    'num':'student number',
    'name':'student name',
    'sex':'student sex',
    'age':'student age'#出生年月日,当前系统系统时间计算年龄
}

def find():
    student_name=input('Name:')
    for key in people:
        if people[key]['name']==student_name:
            request = input('find :num(n) or sex (s) or age (a)?')#重名会查找多次
            if request == 'n':
                choose_key = 'num'
                print("{}'s {} is {}.".format(student_name,labels[choose_key],key))              
            if request == 's':
                choose_key = 'sex'
                print("{}'s {} is {}.".format(student_name,labels[choose_key],people[key][choose_key]))
            if request == 'a':
                choose_key = 'age'
                birth_str=people[key][choose_key] #计算年龄
                birth = datetime.datetime.strptime(birth_str, '%Y-%m-%d')
                now = datetime.datetime.now().strftime('%Y-%m-%d')                
                now = datetime.datetime.strptime(now,'%Y-%m-%d')
                if now.month < birth.month:
                    age = now.year-birth.year-1
                if now.month > birth.month:
                    age = now.year-birth.year
                if now.month == birth.month and now.day < birth.day:
                    age = now.year-birth.year-1
                if now.month == birth.month and now.day > birth.day:
                    age = now.year-birth.year    

                print("{}'s {} is {}.".format(student_name,labels[choose_key],age))
            

def count():
    age_matrix=[0]*6 #1-5,6-10,11-15,16-20,21-25,other    
    for key in people:
        birth_str=people[key]['age']
        birth = datetime.datetime.strptime(birth_str, '%Y-%m-%d')
        now = datetime.datetime.now().strftime('%Y-%m-%d')                
        now = datetime.datetime.strptime(now,'%Y-%m-%d')
        if now.month < birth.month:
            age = now.year-birth.year-1
        if now.month > birth.month:
            age = now.year-birth.year
        if now.month == birth.month and now.day < birth.day:
            age = now.year-birth.year-1
        if now.month == birth.month and now.day > birth.day:
             age = now.year-birth.year
             
        if age>=1 and age<=5:
            age_matrix[0]=age_matrix[0]+1
        if age>=6 and age<=10:
            age_matrix[1]=age_matrix[1]+1
        if age>=11 and age<=15:
            age_matrix[2]=age_matrix[2]+1
        if age>=16 and age<=20:
            age_matrix[3]=age_matrix[3]+1
        if age>=21 and age<=25:
            age_matrix[4]=age_matrix[4]+1
        if age>=26:
            age_matrix[5]=age_matrix[5]+1
    print(("{}年龄段:{}人,{}年龄段:{}人,{}年龄段:{}人,{}年龄段:{}人,{}年龄段:{}人,{}年龄段:{}人.".
          format('1-5',age_matrix[0],'6-10',age_matrix[1],'11-15',age_matrix[2],'16-20',age_matrix[3],'21-25',age_matrix[4],'other',age_matrix[5])))

             
def main():
    flag = 'c'
    print(people)
    while flag == 'c':
        find()
        count()
        flag = input('continue (c) or stop (s)')

main()

上面源程序里的时间模块

birth_str=people[key][choose_key] #获取字典里学生的出生日期
birth = datetime.datetime.strptime(birth_str, '%Y-%m-%d') #用-分割学生的出生日期,获取年月日
now = datetime.datetime.now().strftime('%Y-%m-%d') #获取今天的日期                
now = datetime.datetime.strptime(now,'%Y-%m-%d')    #分割今天的日期获取年月日
if now.month < birth.month: #如果学生月份比今天大,他肯定没过生日,则年份相减再减一
   age = now.year-birth.year-1
if now.month > birth.month:    #如果学生月份比今天小,他过生日了,则年份相减
   age = now.year-birth.year
if now.month == birth.month and now.day < birth.day: #如果月份相等,学生日比今天大,他没过生日
   age = now.year-birth.year-1
if now.month == birth.month and now.day > birth.day: #如果月份相等,学生日比今天小,他过生日了
   age = now.year-birth.year    

运行截图

### Python `datetime` 模块使用方法 #### 创建日期时间对象 可以通过多种方式创建 `datetime` 对象。最常见的方式是通过指定年、月、日来实例化一个 `datetime` 对象。 ```python from datetime import datetime dt = datetime(2023, 10, 5, 14, 30, 0) # 年,月,日,小时,分钟,秒 print(dt) ``` 上述代码展示了如何利用参数 `(year, month, day, hour=0, minute=0, second=0)` 来初始化一个具体的日期时间对象[^4]。 #### 当前日期时间和格式化输出 可以获取当前的日期和时间并将其格式化为字符串形式: ```python now = datetime.now() # 获取当前日期时间 formatted_date = now.strftime("%Y-%m-%d %H:%M:%S") # 格式化输出 print(formatted_date) ``` 这使用的 `%Y`, `%m`, `%d` 等占位符分别代表四位数的年份、两位数的月份以及两位数的日份数字[^5]。 #### 时间差计算 `timedelta` 型表示两个 `date` 或者 `datetime` 实例之间的时间间隔。下面的例子演示了如何减少一天两小时三分钟四秒钟的时间量: ```python from datetime import timedelta delta = timedelta(days=-1, hours=-2, minutes=-3, seconds=-4) new_time = dt + delta print(new_time) ``` 此段代码中的变量 `add_info` 被定义成了一种负向的时间增量[^3]。 #### 字符串转日期时间 如果有一个日期字符串并且希望将其转化为 `datetime` 对象,则可采用如下方法实现这一转换过程: ```python str_to_dt = datetime.strptime('2023-10-05', '%Y-%m-%d') # 将字符串解析为datetime对象 print(str_to_dt) ``` 这段代码实现了从特定格式的字符串到 `datetime` 对象的转变功能。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值