代码之家  ›  专栏  ›  技术社区  ›  Karn Kumar

基于datetime计算年龄的Python最佳语法方法

  •  1
  • Karn Kumar  · 技术社区  · 7 年前

    在网上搜索后得到了以下两种方法来确定一个人的年龄。 只是想知道是否有更好的综合方法来计算和编写3.x版本的python。

    第一个办法。。。

    $ cat birth1.py
    #!/grid/common/pkgs/python/v3.6.1/bin/python3
    import datetime
    year = datetime.datetime.now().year # getting current year from the system
    year_of_birth = int(input("Enter Your Birth Year: "))
    print("You are  %i Year Old" %  (year - year_of_birth))
    

    结果。。

    $ ./birth1.py
    Enter Your Birth Year: 1981
    You are  37 Year Old
    

    第二条路。。。。

    $ cat birth2.py
    #!/grid/common/pkgs/python/v3.6.1/bin/python3
    from datetime import datetime, date
    
    print("Your date of birth (dd/mm/yyyy)")
    date_of_birth = datetime.strptime(input("Please Put your age here: "), "%d/%m/%Y")
    
    def calculate_age(born):
        today = date.today()
        return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
    
    age = calculate_age(date_of_birth)
    print("You are  %i Year Old." %  (age))
    

    结果会产生。。

    $ ./birth2.py
    Your date of birth (dd/mm/yyyy)
    Please Put your age here: 22/09/2015
    You are  2 Year Old.
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   J_H    7 年前

    利用 timedelta .

    import datetime as dt
    
    
    def years_ago(start: str):
        sec_per_year = 365.24 * 24 * 60 * 60
        delta = dt.datetime.now() - dt.datetime.strptime(start, '%d/%m/%Y')
        return delta.total_seconds() / sec_per_year
    
    
    if __name__ == '__main__':
        print(int(years_ago(input('What is your date of birth (dd/mm/yyyy) ? '))))