Flask---SQLAlchemy中從datetime字段獲取某月份的數據


需求:

在使用Flask開發項目,需要按月份進行匯總,在數據庫的歷史記錄中,我使用了datetime記錄日期和時間,那么如何獲取某月份的所有數據呢?

第一種方法:

一種方法是先獲取那個月份的第一天和最后一天的datetime,再使用between,例如:

# 基於Flask的SQLAlchemy

# models
class History(db.Model):
    __tablename__ = 'historys'
    id = db.Column(db.Integer, primary_key=True)
    date= db.Column(db.Date)
# firstDay:某年某月的第一天,datetime類型
# lastDay:某年某月的最后一天,datetime類型
historys = History.query.filter(History.date.between(firstDay, lastDay)).all()

關於獲取某月份的第一天和最后一天,可以參考這里

def getMonthFirstDayAndLastDay(year=None, month=None):
    """
    :param year: 年份,默認是本年,可傳int或str類型
    :param month: 月份,默認是本月,可傳int或str類型
    :return: firstDay: 當月的第一天,datetime.date類型
              lastDay: 當月的最后一天,datetime.date類型
    """
    if year:
        year = int(year)
    else:
        year = datetime.date.today().year

    if month:
        month = int(month)
    else:
        month = datetime.date.today().month

    # 獲取當月第一天的星期和當月的總天數
    firstDayWeekDay, monthRange = calendar.monthrange(year, month)

    # 獲取當月的第一天
    firstDay = datetime.date(year=year, month=month, day=1)
    lastDay = datetime.date(year=year, month=month, day=monthRange)

    return firstDay, lastDay

 

第二種方法(更好,推薦):

第一種方法其實是笨了一點,但是還可以用。后來我思考能不能不用between,不然還要計算某月的第一天和最后一天。后來查閱資料發現有更好的查詢方法。

這個方法要使用extract函數,這個函數可以從datetime字段中分解出年月。不過在flask_sqlalchemy中沒有extract,所以只能從sqlalchemy包導入。

from sqlalchemy import extract

之后只需要這么寫,就可以獲取某月份的所有數據了

# 獲取12月份的所有數據
historys = History.query.filter(extract('month', History.date) == 12).all()

但是用上面的查詢會把往年的12月也查詢出來,那么就加上年份的查詢

from sqlalchemy import extract, and_

historys = History.query.filter(and_(
    extract('year', History.date) == 2016,
    extract('month', History.date) == 12
).all()

自此,2016年12月份的所有記錄就可以查詢出來了。

 

參考資料:

https://blog.csdn.net/huoyuan_zh/article/details/7322160

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM