Subtracting Dates With Python

后端 未结 5 833
攒了一身酷
攒了一身酷 2020-12-30 21:19

I\'m working on a simple program to tell an individual how long they have been alive.

I know how to get the current date, and get their birthday. The only problem is

5条回答
  •  心在旅途
    2020-12-30 21:57

    Create a datetime.datetime from your date:

    datetime.datetime.combine(birthdate, datetime.time())
    

    Now you can subtract it from datetime.datetime.now().

    >>> from datetime import date, datetime, time
    >>> bday = date(1973, 4, 1)
    >>> datetime.now() - datetime.combine(bday, time())
    datetime.timedelta(14392, 4021, 789383)
    >>> print datetime.now() - datetime.combine(bday, time())
    14392 days, 1:08:13.593813
    

提交回复
热议问题