Abrar Khan
Abrar Khan

Reputation: 65

Procedure for explicit type conversion in python from a float to int

I am composing a program which allows me to calculate a person's age in days- accounting for every day including leap days, and irregular number of days in months. Here is a line of code:

number_of_days = (((year2 - year1) * 12) + (month2 - month1)) * 30.4375 + (day2 - day1)

I got the value 30.4375 by dividing 365.25 by 12.

Now I only need to store the integer part in number_of_days. How do I do that?

Help is really appreciated!

P.S. All variable values are int values

Upvotes: 0

Views: 3874

Answers (5)

Thierry Lathuille
Thierry Lathuille

Reputation: 24232

If your goal is to calculate the number of days between dates you can use the datetime module:

import datetime
birth = datetime.date(1967,11,14)
today = datetime.date.today()

number_of_days = (today - birth).days

Upvotes: 2

BrenBarn
BrenBarn

Reputation: 251363

Just call int:

number_of_days = int((((year2 - year1) * 12) + (month2 - month1)) * 30.4375 + (day2 - day1))

Upvotes: 3

aldeb
aldeb

Reputation: 6828

You can either use int:

number_of_days = int((((year2 - year1) * 12) + (month2 - month1)) * 30.4375 + (day2 - day1))

or math.floor:

import math

number_of_days = math.floor((((year2 - year1) * 12) + (month2 - month1)) * 30.4375 + (day2 - day1))

But then number_of_days will be a float, so I think the first solution is better.

Upvotes: 4

0x90
0x90

Reputation: 40982

consider to use round instead of converting that is more accurate:

import math
int(math.round((((year2 - year1) * 12) + (month2 - month1)) * 30.4375 + (day2 - day1)))

Upvotes: 2

Silvertiger
Silvertiger

Reputation: 1680

Could you just use the floor function?

number_of_days = math.floor((((year2 - year1) * 12) + (month2 - month1)) * 30.4375 + (day2 - day1))

Upvotes: 2

Related Questions