[Python fun] – How many days have you lived on Earth?

Sometimes, you may encounter some fun application on Facebook such as: ‘How many days have you lived on Earth?’ or ‘Guess how long you will live’. Well, that’s nothing magical. I’ll show you how to do that in Python with datetime library.

To get the current time, we use:

[in 1]: import datetime

[in 2]: datetime.datetime.now()
[out 2]: datetime.datetime(2019, 2, 22, 23, 2, 12, 340517)

The order is: year/month/day/hour/minute/second/millisecond

Now you see how simple it is. To know how many days you have been on Earth, use a minus operation only. For example, you were born in 1/5/1990 at 00:00:00


[in 3]: dt = datetime.datetime.now() - datetime.datetime(
1990, 5, 1, 0, 0, 0
)

[in 4]: print(dt)
[out 4]: 10524 days, 23:06:15.591314

And to get your age, that’s bullshit :)) They only use random library, for example, from Facebook info, the app knows you are 29 years old, so all it needs to do is to generate a random number between your age and, well, maybe 100 or above.

[in 5]: import random

Or you can directly import randint since we only use this function of random library.

[in 6]: from random import randint

randint(start, end) will generate a random integer number from start to end, including start and end)

[in 7]: randint(29, 100)
[out 7]: 67

That’s it. Hope you have some fun with Python.

Leave a Reply

Your email address will not be published. Required fields are marked *