Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out if a date is more than 30 days old

I want to know if insertion_date is older than 30 days. This should detect down to the minute and second of the current time. The value in insertion_date will be dynamically pulled from an API.

Current code only detects up to the day, i need the accuracy to up to the second.

import datetime
import dateutil.parser

insertion_date = dateutil.parser.parse('2017-08-30 14:25:30')
right_now_30_days_ago = datetime.datetime.today() - datetime.timedelta(days=30)

print right_now_30_days_ago #2017-08-31 12:18:40.040594
print insertion_date #2017-08-30 14:25:30

if insertion_date > right_now_30_days_ago:
    print "The insertion date is older than 30 days"

else:
    print "The insertion date is not older than 30 days"
like image 443
Franco Avatar asked Sep 05 '17 02:09

Franco


People also ask

How do you check if a date is older than 30 days in Java?

1. Java 8 isBefore() First minus the current date and then uses isBefore() to check if a date is a certain period older than the current date. 1.1 This example checks if a date is 6 months older than the current date.

How do you check if a date is greater than 30 days in Javascript?

getTime() + thirtyDaysInMs; if (date > timestampThirtyDaysInFuture) { console. log('date is more than 30 days into the future'); return true; } else { console. log('date is NOT more than 30 days into the future'); return false; } } // 👇️ true console.

How do you check if a date is before another date?

To check if a date is before another date, compare the Date objects, e.g. date1 < date2 . If the comparison returns true , then the first date is before the second, otherwise the first date is equal to or comes after the second.


2 Answers

you need to do something on similar lines:

from datetime import datetime, timedelta
time_between_insertion = datetime.now() - insertion_date

if  time_between_insertion.days>30:
    print "The insertion date is older than 30 days"

else:
    print "The insertion date is not older than 30 days"
like image 74
Daniyal Ahmed Avatar answered Sep 29 '22 10:09

Daniyal Ahmed


from datetime import datetime, timedelta

print(datetime.now())
datetime.datetime(2017, 9, 5, 7, 25, 37, 836117)

print(datetime.now() - timedelta(days=30))
datetime.datetime(2017, 8, 6, 7, 25, 51, 723674)

As you can see here, it is accurate down to seconds.

The problem is in datetime.today(). You should use datetime.now() instead of datetime.today():

time_since_insertion = datetime.now() - insertion_date

if time_since_insertion.days > 30:
   print("The insertion date is older than 30 days")
else:
  print("The insertion date is not older than 30 days")

Hope it helps!

like image 23
Jahongir Rahmonov Avatar answered Sep 29 '22 10:09

Jahongir Rahmonov