python根据出生日期返回年龄的方法

yipeiwu_com6年前Python基础

本文实例讲述了python根据出生日期返回年龄的方法。分享给大家供大家参考。具体实现方法如下:

def CalculateAge(self, Date):
    '''Calculates the age and days until next birthday from the given birth date'''
    try:
      Date = Date.split('.')
      BirthDate = datetime.date(int(Date[0]), int(Date[1]), int(Date[2]))
      Today = datetime.date.today()
      if (Today.month > BirthDate.month):
        NextYear = datetime.date(Today.year + 1, BirthDate.month, BirthDate.day)
      elif (Today.month < BirthDate.month):
        NextYear = datetime.date(Today.year, Today.month + (BirthDate.month - Today.month), BirthDate.day)
      elif (Today.month == BirthDate.month):
        if (Today.day > BirthDate.day):
          NextYear = datetime.date(Today.year + 1, BirthDate.month, BirthDate.day)
        elif (Today.day < BirthDate.day):
          NextYear = datetime.date(Today.year, BirthDate.month, Today.day + (BirthDate.day - Today.day))
        elif (Today.day == BirthDate.day):
          NextYear = 0
      Age = Today.year - BirthDate.year
      if NextYear == 0: #if today is the birthday
        return '%d, days until %d: %d' % (Age, Age+1, 0)
      else:
        DaysLeft = NextYear - Today
        return '%d, days until %d: %d' % (Age, Age+1, DaysLeft.days)
    except:
      return 'Wrong date format'

使用方法如下:

print CheckDate('2000.05.05')

希望本文所述对大家的Python程序设计有所帮助。

相关文章

Python 基础教程之str和repr的详解

Python str和repr的详解 str可以将值转化为合理的字符串形式,以便用户可以理解; repr会以合法Python表达式的形式来表达值。 举例如下: # str输出用户...

Python中遍历字典过程中更改元素导致异常的解决方法

先来回顾一下Python中遍历字典的一些基本方法: 脚本: #!/usr/bin/python dict={"a":"apple","b":"banana","o":"orange...

Python KMeans聚类问题分析

Python KMeans聚类问题分析

今天用python实现了一下简单的聚类分析,顺便熟悉了numpy数组操作和绘图的一些技巧,在这里做个记录。 from pylab import * from sklearn.clus...

Python数学形态学实例分析

Python数学形态学实例分析

本文实例讲述了Python数学形态学。分享给大家供大家参考,具体如下: 一 原始随机图像 1、代码 import numpy as np import matplotlib.pypl...

Python中input和raw_input的一点区别

使用input和raw_input都可以读取控制台的输入,但是input和raw_input在处理数字时是有区别的 当输入为纯数字时: input返回的是数值类型,如int,float...