Home > Blockchain >  How to compare two dates and see if they are within 1 year?
How to compare two dates and see if they are within 1 year?

Time:06-27

I need to scrape a date off of a web page and compare it to todays date and see if the scraped date is within 1 year of today and produce a True of False statement.

I spend about 4 hours yesterday trying to get this to work but kept getting errors from every example I could find on the internet when trying to use them in this implementation.

Eventually I got something that worked without errors but it produced the incorrect result.

Unfortunately I somehow managed to delete that script last night and now I'm back at square zero. Instead of beating my head against the wall can someone inform me of the correct way to do this?

I'm trying to do something like this

contract_end_date = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="lbl_CONTRACT_EXPIRES"]'))).text
(example, contract_end_date = "09/25/2022")
if contract_end_date <= todays_date_plus_1_year:
   return True
else:
   return False

Much appreciate the help

CodePudding user response:

This should be doable with datetime.timedelta.

Just make sure that your contract_end_date is a datetime object.

Edit: Added the str to datetime conversion

from datetime import datetime, timedelta

def expires_within_a_year(date_str):
    """date_str format must be like this: 09/25/2022"""
    contract_end_date = datetime.strptime(date_str, "%m/%d/%Y")
    today = datetime.now()
    one_year = timedelta(days=365)
    one_year_later = today   one_year
    # true if within the next 365 days (so if today is 09/25/2022, enddate 09/24/2023 would return true, enddate 09/25/2023 would return false)
    return contract_end_date < one_year_later

CodePudding user response:

a little bit shorter:

from datetime import datetime

def expires_within_a_year(date_str):
    contract_end_date = datetime.strptime(date_str, "%m/%d/%Y")
    return (contract_end_date - datetime.now()).days < 365

expires_within_a_year('09/25/2022')  # True
  • Related