简介
在数据开发中常需要各种时间维度的统计、为了方便日常开发方便、记录一下。
代码实现如下:
import datetime
from datetime import timedelta
YYYYmmdd = '%Y-%m-%d'
# 获取当前日期季度最开始时间
def get_first_quarter(thedate):
now = datetime.datetime.strptime(str(thedate), YYYYmmdd)
month = (now.month - 1) - (now.month - 1) % 3 + 1
this_quarter_start = datetime.datetime(now.year, month, 1).strftime(YYYYmmdd)
return this_quarter_start
# 获取当季度最后时间
def get_last_quarter(thedate):
if thedate >= thedate[0:4] + '-09-30':
return thedate[0:4] + '-12-31'
else:
now = datetime.datetime.strptime(str(thedate), YYYYmmdd)
month = (now.month - 1) - (now.month - 1) % 3 + 1
this_quarter_end = datetime.datetime(now.year, month + 3, 1) - timedelta(days=1)
return this_quarter_end.strftime(YYYYmmdd)
def get_n_month_first(thedate, num):
day = datetime.datetime.strptime(thedate, YYYYmmdd)
year = day.year
month = day.month
if day.month - num <= 0:
year -= 1
month = 12 + day.month - num
else:
month -= num
future_mouth_first = datetime.datetime(year, month, 1, 23, 59, 59)
return future_mouth_first.strftime(YYYYmmdd)
# 获得当月第一天
def get_month_first(thedate):
return get_n_month_first(thedate, 0)
# 获得当月最后一天
def get_month_end(thedate):
day = datetime.datetime.strptime(thedate, "%Y-%m-%d")
month = day.month
year = day.year
if month == 12:
month = 0
year = year + 1
future_mouth_first = datetime.datetime(year, month + 1, 1, 23, 59, 59)
this_month = future_mouth_first - datetime.timedelta(days=1)
return this_month.strftime('%Y-%m-%d')
# 一年中第一天
def get_first_year(thedate):
now = datetime.datetime.strptime(str(thedate), YYYYmmdd)
this_year_start = datetime.datetime(now.year, 1, 1)
return this_year_start.strftime(YYYYmmdd)
# 一年中最后一天
def get_last_yaer(thedate):
now = datetime.datetime.strptime(str(thedate), YYYYmmdd)
this_year_end = datetime.datetime(now.year + 1, 1, 1) - timedelta(days=1)
return this_year_end.strftime(YYYYmmdd)
# 周一日期
def get_week_first(thedate):
from datetime import timedelta
today = datetime.datetime.strptime(str(thedate), "%Y-%m-%d")
return datetime.datetime.strftime(today - timedelta(today.weekday()), "%Y-%m-%d")
# 周末日期
def get_week_end(thedate):
thedate_star=get_week_first(thedate)
day = datetime.datetime.strptime(thedate_star, YYYYmmdd)
week_end_before = datetime.datetime.strftime(day + datetime.timedelta(6), YYYYmmdd)
return week_end_before
print('------------季度: 季初&季末----------------')
print(get_first_quarter('2021-08-01'))
print(get_last_quarter('2021-08-01'))
print('-------------月份:月初&月末-----------------')
print(get_month_first('2021-08-02'))
print(get_month_end('2021-08-02'))
print('-------------年份: 年初&年末-----------------')
print(get_first_year('2021-08-02'))
print(get_last_yaer('2021-08-02'))
print('-------------周: 周初&周末-----------------')
print(get_week_first('2021-08-02'))
print(get_week_end('2021-08-02'))