我找到了这个片段:
def timesince(dt, default="just now"):
now = datetime.utcnow()
diff = now - dt
periods = (
(diff.days / 365, "year", "years"),
(diff.days / 30, "month", "months"),
(diff.days / 7, "week", "weeks"),
(diff.days, "day", "days"),
(diff.seconds / 3600, "hour", "hours"),
(diff.seconds / 60, "minute", "minutes"),
(diff.seconds, "second", "seconds"),
)
for period, singular, plural in periods:
if period:
return "%d %s ago" % (period, singular if period == 1 else plural)
return default
并且想要在Google Appegine中对我的数据库进行查询时在输出中使用它。 我的数据库看起来像这样:
class Service(db.Model):
name = db.StringProperty(multiline=False)
urla = db.StringProperty(multiline=False)
urlb = db.StringProperty(multiline=False)
urlc = db.StringProperty(multiline=False)
timestampcreated = db.DateTimeProperty(auto_now_add=True)
timestamplastupdate = db.DateTimeProperty(auto_now=True)
在我想做的webapp requesthandler的主页中:
elif self.request.get('type') == 'list':
q = db.GqlQuery('SELECT * FROM Service')
count = q.count()
if count == 0:
self.response.out.write('Success: No services registered, your database is empty.')
else:
results = q.fetch(1000)
for result in results:
resultcreated = timesince(result.timestampcreated)
resultupdated = timesince(result.timestamplastupdate)
self.response.out.write(result.name + '\nCreated:' + resultcreated + '\nLast Updated:' + resultupdated + '\n\n')
我做错了什么?我在使用代码片段格式化代码时遇到了麻烦。
我应该做以下哪一项?
此?
def timesince:
class Service
class Mainpage
def get(self):
还是这个?
class Service
class Mainpage
def timesince:
def get(self):
我对Python并不太熟悉,并且非常感谢如何解决这个问题。谢谢!
答案 0 :(得分:0)
我不完全清楚你遇到的问题是什么,所以请耐心等待。回溯将有所帮助。 :)
timesince()不需要任何成员变量,所以我认为它不应该在其中一个类中。如果我在你的情况下,我可能会将timesince放在自己的文件中,然后将该模块导入到定义Mainpage的文件中。
如果您将它们全部放在同一个文件中,请确保您的间距一致,并且没有任何标签。
答案 1 :(得分:0)
这对我来说很好用:
from datetime import datetime
def timesince(dt, default="now"):
now = datetime.now()
diff = now - dt
periods = (
(diff.days / 365, "year", "years"),
(diff.days / 30, "month", "months"),
(diff.days / 7, "week", "weeks"),
(diff.days, "day", "days"),
(diff.seconds / 3600, "hour", "hours"),
(diff.seconds / 60, "minute", "minutes"),
(diff.seconds, "second", "seconds"),
)
for period, singular, plural in periods:
if period >= 1:
return "%d %s ago" % (period, singular if period == 1 else plural)
return default
timesince(datetime(2016,6,7,12,0,0))
timesince(datetime(2016,6,7,13,0,0))
timesince(datetime(2016,6,7,13,30,0))
timesince(datetime(2016,6,7,13,50,0))
timesince(datetime(2016,6,7,13,52,0))