Skip to content

Latest commit

 

History

History
98 lines (60 loc) · 2.77 KB

获得当天-当周-当月的开始结束时间.md

File metadata and controls

98 lines (60 loc) · 2.77 KB

我们有时在查询数据库的时候需要查询当日、当自然周、当自然月的数据。我们写三个函数来获取这些时间区间。

获取今日的开始和结束时间戳

import time
import datetime

def get_day_region():
    today = datetime.date.today() 
    tomorrow = today + datetime.timedelta(days=1)
    start_time = int(time.mktime(time.strptime(str(today), '%Y-%m-%d')))
    end_time = int(time.mktime(time.strptime(str(tomorrow), '%Y-%m-%d'))) - 1

    return start_time, end_time

获取当前自然周的开始和结束时间戳

from datetime import datetime, timedelta
import time

def get_week_region():

    today = datetime.today().replace(hour=0, minute=0, second=0, microsecond=0)

    week_pos = today.weekday()

    start_date = today - timedelta(days=week_pos)
    end_date = today + timedelta(days=(7 - week_pos))

    start_time = int(time.mktime(start_date.timetuple()))
    end_time = int(time.mktime(end_date.timetuple())) - 1

    return start_time, end_time

获取当前自然周的开始和结束时间戳

from datetime import datetime, timedelta
import time

def get_week_region():

    today = datetime.today().replace(hour=0, minute=0, second=0, microsecond=0)

    week_pos = today.weekday()

    start_date = today - timedelta(days=week_pos)
    end_date = today + timedelta(days=(7 - week_pos))

    start_time = int(time.mktime(start_date.timetuple()))
    end_time = int(time.mktime(end_date.timetuple())) - 1

    return start_time, end_time

其中today.weekday()返回当前是周几的索引 周一为0 周二为1依次类推 周日为6

获取当前自然月的开始和结束时间戳

import calendar
from datetime import datetime, timedelta
import time


def get_month_region():

    today = datetime.today().replace(hour=0, minute=0, second=0, microsecond=0)

    start_date = today.replace(day=1)

    _, days_in_month = calendar.monthrange(start_date.year, start_date.month)

    end_date = start_date + timedelta(days=days_in_month)

    start_time = int(time.mktime(start_date.timetuple()))
    end_time = int(time.mktime(end_date.timetuple())) - 1

    return start_time, end_time

其中的calendar.monthrange返回当月1号对应周几和当月天数

求微信赞赏 求支付宝赞赏 加微信好友

如果您觉得此文对您有帮助 可以选择微信或支付宝支持我一下或者加我微信好友 一起搞py交易