从python datetimefield对象获取年份

时间:2015-06-09 12:07:06

标签: python python-2.7

print SDstDate

给出了以下输出:

<peewee.DateTimeField object at 0x7fd9dc8b0950>

print SDstDate.year

给出了以下输出:

<peewee.Func object at 0x7f3737b0ef10>

请帮助我如何从SDstDate中提取提取年份。 SDstDate是一个dattetimefield对象,我通过peewee从mysql数据库中获取。

1 个答案:

答案 0 :(得分:2)

因此,假设您有一个带有DateTimeField的模型,指示何时发布博客条目:

class Blog(Model):
    timestamp = DateTimeField()

要从帖子列表中检索年份,只需执行以下操作:

for post in Blog.select():
    print post.timestamp.year

由于timestamp字段中的值是Python datetime,因此您可以访问其中的属性,如yearmonth等。

另一方面,对于查询在给定年份发布的博客条目,您可以写:

posts_this_year = Blog.select().where(Blog.timestamp.year == 2015)
for post in posts_this_year:
    # ... do whatever ...