Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading