I've created a MySQL table with these fields:
id - int - auto_increment
dt - DateTime
desc - VARCHAR 255
Now I would like know know how to select only the years from this table with Peewee in Python. Equal years should be removed.
In SQL I would simply do SELECT DISTINCT YEAR(dt) AS yr from data;
to get the desired result.
I'm aware of the db.execute_sql
method to execute a raw SQL-query. I wonder however if there is a cleaner way.
Thanks and best regards.
You can do it like this:
query = Data.select(Data.dt.year.distinct())
for distinct_ts, in query.tuples():
print(distinct_ts)
To sort by date:
distinct_ts = Data.dt.year.distinct()
query = Data.select(distinct_ts.alias('timestamp')).order_by(distinct_ts)
for row in query:
print(row.timestamp)