簡體   English   中英

當前星期,月份,年份的日期范圍。 Python /燒瓶

[英]Date range of current week, month, year. Python/Flask

我在試圖過濾查詢的數據模型上有一個datefield(created_on)。 我試圖按當前星期,月份,年份進行過濾。 請勿將其與去年的一周前,一個月前相混淆。 (不采用今天的日期,並減去X daterange / timedelta以獲得最后7、31、365天的價值)

例如:

當前周:如果星期三是7日,那么我想從5月1日至11日進行過濾。

當前月份(如果是2月16日),我想在2月1日至2月29日之前進行過濾。

當年如果是2016年3月3日,我想過濾2016年1月1日至2016年12月31日。

語音示例:

.filter(Table.created_on BETWEEN FIRST AND LAST DAY OF THIS WEEK/MONTH/YEAR)

在所有情況下,您都希望LOWER_BOUND < Table.created_on < UPPER_BOUND 可能需要將其分為兩部分,不確定sqlalchemy是否可以自動執行該操作。

當前一周,您需要減去0到6天(具體取決於一周中的星期幾)來獲得下限,將0到6之間相加即可獲得上限。

當前月份,找到當前月份和年份,下限為YEAR-MONTH-01,上限為YEAR-MONTH-DAYS_IN_MONTH。

本年度,下限為YEAR-01-01,上限為YEAR-12-31。

要獲取此信息,請嘗試使用標准庫中的datetime包。 除了leap年之外,這確實很簡單。 除非您處理精確的時間(遇到紀元限制或seconds秒或時區或DST)或“ N個月/年前”(在這種情況下,您必須處理“ 1個月之前12月31日”,“ 2月29日之前的1年”等)。 只要您不使用可變持續時間(例如,幾個月或幾年)作為單位,並且您不需要精確的時鍾時間,那么就可以安全地將天數視為單位,甚至不涉及任何算術運算。

# In all
from datetime import date, timedelta
today = date.today()

然后,在一周內:

weekday = today.weekday()
# lower bound
mon = today - timedelta(days=weekday)
# upper bound
sun = today + timedelta(days=(6 - weekday))

對於月份:

days_per_month = {1: 31, 2: 29, 3: 31, ...} # you can fill this in yourself
# lower bound
first = today.replace(day=1)
# upper bound
try:
    last = today.replace(day=days_per_month[today.month])
except ValueError:
    if today.month == 2:  # Not a leap year
        last = today.replace(day=28)
    else:
        raise  # just to be safe, in case there's some other error I missed

而對於一年:

# lower bound
janfirst = today.replace(month=1, day=1)
# upper bound
declast = today.replace(month=12, day=31)

在所有情況下,如果保證列的內容是過去的(例如,如果它們是將行添加到表中的日期),則可以用當前日期替換上限。 也許是明天的查詢,如果查詢從午夜開始很近,之后又有新的條目。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM