Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if datetime is older than 20 seconds

This is my first time here so I hope I post this question at the right place. :)

I need to build flood control for my script but I'm not good at all this datetime to time conversions with UTC and stuff. I hope you can help me out. I'm using the Google App Engine with Python. I've got a datetimeproperty at the DataStore database which should be checked if it's older than 20 seconds, then proceed.

Could anybody help me out?

So in semi-psuedo:

q = db.GqlQuery("SELECT * FROM Kudo WHERE fromuser = :1", user)
lastplus = q.get()

if lastplus.date is older than 20 seconds:
print"Go!"
like image 808
Jelle Avatar asked Mar 07 '10 22:03

Jelle


People also ask

How do you find the difference in seconds in Python?

Time Difference between two timestamps in Python Next, use the fromtimestamp() method to convert both start and end timestamps to datetime objects. We convert these timestamps to datetime because we want to subtract one timestamp from another. Next, use the total_seconds() method to get the difference in seconds.

How do I get Timedelta in Python?

timedelta() method. To find the difference between two dates in Python, one can use the timedelta class which is present in the datetime library. The timedelta class stores the difference between two datetime objects.

How can you find the difference in time between two datetime objects time_1 and time_2?

Subtracting the later time from the first time difference = later_time - first_time creates a datetime object that only holds the difference.

How do I check if a date is less than today in Python?

strftime("%m/%d/%Y")) print ("This is today's date: " + myDate) if datd <= myDate: # if datd is is earlier than todays date print (" Password expired. ") else: print (" Password not expired. ") input(" Press Enter to exit. ")


2 Answers

You can use the datetime.timedelta datatype, like this:

import datetime
lastplus = q.get()
if lastplus.date < datetime.datetime.now()-datetime.timedelta(seconds=20):
    print "Go"

Read more about it here: http://docs.python.org/library/datetime.html

Cheers,

Philip

like image 176
mojbro Avatar answered Oct 22 '22 04:10

mojbro


Try this:

from datetime import timedelta, datetime
if lastplus.date < datetime.utcnow() + timedelta(seconds = -20):
    print "fee fie fo foo!"
like image 4
Cameron Avatar answered Oct 22 '22 03:10

Cameron