Home > Net >  how to compare given date (string) is current date to last 8 date or not?
how to compare given date (string) is current date to last 8 date or not?

Time:12-01

I have an one date in a string. How can I figure out this date REFRESH = ("2021-11-25 00:27:23") to current date from last 8 days

from datetime import datetime
from datetime import timedelta
REFRESH =  ("2021-11-25 00:27:23")
today = datetime.now()
n_days_ago = today - timedelta(days=7)
print(today, n_days_ago)

I am stuck here.

I need data like if refresh date is true from current date from last 8 days. "Pass"

CodePudding user response:

if your intention is to print current date and days passed from REFRESH I think this one will work

refresh_as_datetime=datetime.strptime(REFRESH,"%Y-%m-%d %H:%M:%S")
delta = datetime.now()-refresh_as_datetime
print(today, delta.days)

CodePudding user response:

You need to convert string to datetime object in order to compare, useful function for that is strptime() which takes 2 params: string and date format of the string.

Next use date() function to get just the date without time, since you want to compare the dates.

Example:

from datetime import datetime, timedelta

REFRESH = "2021-11-24 00:27:23"
today = datetime.today()
n_days_ago = today - timedelta(days=7)
if n_days_ago.date() == datetime.strptime(REFRESH, "%Y-%m-%d %H:%M:%S").date():
    print(True)
else:
    print(False)
  • Related