这种方法算是代码量比较小的,同时可以保证求的是本地时区的0点时间戳,返回的是浮点数,需要的话自己转一下int
# 返回时间戳
import time
from datetime import datetime
time.mktime(datetime.now().date().timetuple())
1.获取今天零点和24点
def getTodayDate():
now = datetime.datetime.now()
zero_today = now - datetime.timedelta(hours=now.hour, minutes=now.minute, seconds=now.second,
microseconds=now.microsecond)
last_today = zero_today + datetime.timedelta(hours=23, minutes=59, seconds=59)
return zero_today, last_today
2.获取本周一零点和周日24点
def getWeekDate():
now = datetime.datetime.now()
zero_week = now - datetime.timedelta(days=now.weekday(), hours=now.hour, minutes=now.minute, seconds=now.second,
microseconds=now.microsecond)
last_week = now + datetime.timedelta(days=6 - now.weekday(), hours=23 - now.hour, minutes=59 - now.minute,
seconds=59 - now.second)
return getFormatDate(zero_week), getFormatDate(last_week)
3.获取本月一号零点和最后一天24点
def getMonthDate():
now = datetime.datetime.now()
zero_month = datetime.datetime(now.year, now.month, 1)
last_month = datetime.datetime(now.year, now.month + 1, 1) - datetime.timedelta(days=1) + datetime.timedelta(
hours=23, minutes=59, seconds=59)
return getFormatDate(zero_month), getFormatDate(last_month)
4.上周第一天和最后一天
now = datetime.datetime.now()
last_week_start = now - timedelta(days=now.weekday()+7)
last_week_end = now - timedelta(days=now.weekday()+1)
5.上月第一天和最后一天
last_month_end = this_month_start - timedelta(days=1)
last_month_start = datetime.datetime(last_month_end.year, last_month_end.month, 1)
6.今年/去年第一天和最后一天
this_year_start = datetime.datetime(now.year, 1, 1)
this_year_end = datetime.datetime(now.year + 1, 1, 1) - datetime.timedelta(days=1)
last_year_end = this_year_start - datetime.timedelta(days=1)
last_year_start = datetime.datetime(last_year_end.year, 1, 1)