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
As suggested by @[Tomasz Zielinski] and @Williams python-dateutil can do it just 5 lines.
The classic gotcha in this scenario is what to do with people born on the 29th day of February. Example: you need to be aged 18 to vote, drive a car, buy alcohol, etc ... if you are born on 2004-02-29, what is the first day that you are permitted to do such things: 2022-02-28, or 2022-03-01? AFAICT, mostly the first, but a few killjoys might say the latter.
Here's code that caters for the 0.068% (approx) of the population born on that day:
Here's the output:
Update: Use Danny's solution, it's better
In Python 3, you could perform division on
datetime.timedelta
:Expanding on Danny's Solution, but with all sorts of ways to report ages for younger folk (note, today is
datetime.date(2015,7,17)
):Sample code: