最近在做的项目有个统计的功能,需要统计本周,本月的数据,解决这个问题首先要从时间上筛选,那么如何用python获取本周或者本月的第一天和最后一天呢
我们需要用到datetime
import datetime
from datetime import timedelta
首先获取当前的时间
now = datetime.datetime.now()
使用 timedelta
做日期加减那么昨天就是
yesterday = now - timedelta(days=1)
明天就是
tomorrow = now + timedelta(days=1)
本周第一天和最后一天
this_week_start = now - timedelta(days=now.weekday())
this_week_end = now + timedelta(days=6-now.weekday())
本二月第一天和最后一天
this_month_start = datetime.datetime(now.year, now.month, 1)
this_month_end = datetime.datetime(now.year, now.month + 1, 1) - timedelta(days=1)
本年第一天和最后一天
this_year_start = datetime.datetime(now.year, 1, 1)
this_year_end = datetime.datetime(now.year + 1, 1, 1) - timedelta(days=1)
因为项目中用的时间戳,所以还得转成时间戳再筛选
month_first_day = str(int(datetime.datetime(cur.year, cur.month, 1).timestamp()))
对应的SQL
sql = "select uid,sum(something_num) as num from table_name where created_at >= " + month_first_day
viencoding.com版权所有,允许转载,但转载请注明出处和原文链接: https://viencoding.com/article/268