How to check if datetime is older than 20 seconds

和自甴很熟 提交于 2021-02-07 04:42:05

问题


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!"

回答1:


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




回答2:


Try this:

from datetime import timedelta, datetime
if lastplus.date < datetime.utcnow() + timedelta(seconds = -20):
    print "fee fie fo foo!"


来源:https://stackoverflow.com/questions/2398205/how-to-check-if-datetime-is-older-than-20-seconds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!