0

i have a variable that stores the number of years between two dates, if i loop through the codeblock and use it a second time it says i cant minus two dates from each other, yet it works on the first loop to return the difference between two dates. what am i doing wrong?

DOB = datetime(1985,2,28)

while continue_search:
   
    SearchName = str(input("            Name Query: >"))
    
    if first_name.upper() in SearchName.upper():
        if last_name.upper() in SearchName.upper():
            print(f'\n            LAST NAME:  {last_name}')
            print(f'            FIRST NAME: {first_name}')
            print(f'            SEX: {Sex}')
            print(f'            RACE: {Race}')                      
            diff = ((datetime.now() - DOB).days + (datetime.now() - DOB).seconds/86400)/365.2425
            diff = math.floor(diff)
            DOB = DOB.date()
            print(f'            AGE: {diff}       DOB: {DOB}\n')

its on this line:

diff = ((datetime.now() - DOB).days + (datetime.now() - DOB).seconds/86400)/365.2425

that it wont work the second time round.

  • 1
    `DOB = DOB.date()` is the problem. – Andrej Podzimek Aug 07 '22 at 12:48
  • Oh I think I see now. DOB gets reassigned to a date type, but it's used inside the diff method. Which is why it halts on the diff the second time around. – Andy Andromeda Aug 07 '22 at 13:05
  • Also, the calculation is “technically wrong”: Never call `.now()` repeatedly in an expression, you are getting (slightly) different values and risking rare and hard-to-debug bugs. [Does this answer your question?](https://stackoverflow.com/a/72567581/8584929) Calculating a person’s age is a matter of counting the difference in years and then subtracting a year if the person hasn’t had a birthday this year. Some implementations consider also hours / minutes / seconds as part of the birthday, but in most cases such precise data is unavailable, so everyone was “born at midnight”, in a way. – Andrej Podzimek Aug 07 '22 at 13:07
  • An example concerning `.now()`: Compare `now = datetime.now(); now - now` (zero) vs. `datetime.now() - datetime.now()` (nonzero). That said, always cache a single `.now()` for the entire calculation. – Andrej Podzimek Aug 07 '22 at 13:10

0 Answers0