How can I find an age in python from today's date and a persons birthdate? The birthdate is a from a DateField in a Django model.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
import datetime
In your case:
Here is a solution to find age of a person as either years or months or days.
Lets say a person's date of birth is 2012-01-17T00:00:00 Therefore, his age on 2013-01-16T00:00:00 will be 11 months
or if he is born on 2012-12-17T00:00:00, his age on 2013-01-12T00:00:00 will be 26 days
or if he is born on 2000-02-29T00:00:00, his age on 2012-02-29T00:00:00 will be 12 years
You will need to import datetime.
Here is the code:
Some extra functions used in the above codes are:
And
Now, we have to feed get_date_format() with the strings like 2000-02-29T00:00:00
It will convert it into the date type object which is to be fed to get_person_age(date_birth, date_today).
The function get_person_age(date_birth, date_today) will return age in string format.
The simplest way is using
python-dateutil
Slightly modified Danny's solution for easier reading and understanding
That can be done much simpler considering that int(True) is 1 and int(False) is 0:
If you're looking to print this in a page using django templates, then the following might be enough: