Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get month and year from Date field in sqlalchemy?

Tags:

The result should be Date object

Since the day cannot be 'removed', set it to say, 1st day of the month.

Leaving only Month, Year

like image 862
user1608977 Avatar asked Aug 18 '12 15:08

user1608977


People also ask

How do I create a date column in SQLAlchemy?

Bookmark this question. Show activity on this post. class Posts(Base): __tablename__ = 'posts_posts' id = Column(Integer, primary_key = True) user_id = Column(Integer, nullable=False) body = Column(Text, nullable=True) created_at = Column(Date) << is this right?

What does SQLAlchemy all () return?

As the documentation says, all() returns the result of the query as a list.

What is all () in SQLAlchemy?

method sqlalchemy.orm.Query. all() Return the results represented by this Query as a list. This results in an execution of the underlying SQL statement. The Query object, when asked to return either a sequence or iterator that consists of full ORM-mapped entities, will deduplicate entries based on primary key.


1 Answers

You can use following constructs to filter the Date column using either year or month:

.filter(extract('year', Foo.Date) == 2012) .filter(extract('month', Foo.Date) == 12) 

And group_by is also possible:

.group_by(sqlalchemy.func.year(Foo.Date), sqlalchemy.func.month(Foo.Date)) 

Now I haven't tested it, but I assume that this might be slow because these queries result in full table scans, therefore I suggest you invest some time and learn how to use composite columns.

Note: extract() is imported from sqlalchemy.sql

like image 197
plaes Avatar answered Oct 16 '22 11:10

plaes