python几个有用的日期相关函数-月内第N周日期获取
程序员文章站
2022-06-25 18:42:32
...
1、日期相加减
def days_addsub(date_str,days):
date_time = datetime.datetime.strptime(date_str, '%Y-%m-%d')
delta = datetime.timedelta(days=days)
n_days = date_time + delta
return n_days.strftime('%Y-%m-%d')
2、月份内第N周的起始结束日期计算(默认date_str取当月第一天)
def days_addsub_forweek(date_str,weekofmonth):
date_time = datetime.datetime.strptime(date_str, '%Y-%m-%d')
week = date_time.weekday()+1
delta_start = datetime.timedelta(days=7*weekofmonth-week-6)
delta_end = datetime.timedelta(days=7*weekofmonth-week)
last_day = date_str[:8]+str(calendar.monthrange(int(date_str[:4]), int(date_str[5:7]))[1])
last_day = datetime.datetime.strptime(last_day, '%Y-%m-%d')
if date_time + delta_start <= date_time:
weekstart=date_time
else:
weekstart=date_time + delta_start
if date_time + delta_end >= last_day:
weekend = last_day
else:
weekend = date_time + delta_end
if weekstart<=last_day:
return weekstart.strftime('%Y-%m-%d'),weekend.strftime('%Y-%m-%d')
3、月份所有周的起始结束日期列表获取
def getWeek(beginMonth, endMonth):
weekMonthList=[]
for months in monthRange(beginMonth=beginMonth, endMonth=endMonth):
for weekofmonth in (1,2,3,4,5,6):
weekTulp = days_addsub_forweek(date_str=months+'-01', weekofmonth=weekofmonth)
if weekTulp <> None:
weekMonthList.append((months,weekofmonth,weekTulp[0], weekTulp[1]))
return weekMonthList
4、综合使用示例
# -*- coding=utf-8 -*-
import warnings
import calendar
import datetime
warnings.filterwarnings("ignore")
def dateRange(beginDate, endDate):
dates = []
dt = datetime.datetime.strptime(beginDate, "%Y-%m-%d")
date = beginDate[:]
while date <= endDate:
dates.append(date)
dt = dt + datetime.timedelta(1)
date = dt.strftime("%Y-%m-%d")
return dates
def monthRange(beginMonth, endMonth):
months = set([])
mt = datetime.datetime.strptime(beginMonth, "%Y-%m")
month = beginMonth[:]
while month <= endMonth:
months.add(month)
mt = mt + datetime.timedelta(1)
month = mt.strftime("%Y-%m")
monthList = sorted(months)
return monthList
def months_addsub(dt,months):
month = dt.month - 1 + months
year = dt.year + month / 12
month = month % 12 + 1
day = min(dt.day,calendar.monthrange(year,month)[1])
dt = dt.replace(year=year, month=month, day=day)
return str(dt.replace(year=year, month=month, day=day))
def getYesterday():
today = datetime.date.today()
oneday = datetime.timedelta(days=1)
yesterday = today - oneday
return yesterday
def days_addsub(date_str,days):
date_time = datetime.datetime.strptime(date_str, '%Y-%m-%d')
delta = datetime.timedelta(days=days)
n_days = date_time + delta
return n_days.strftime('%Y-%m-%d')
def days_addsub_forweek(date_str,weekofmonth):
date_time = datetime.datetime.strptime(date_str, '%Y-%m-%d')
week = date_time.weekday()+1
delta_start = datetime.timedelta(days=7*weekofmonth-week-6)
delta_end = datetime.timedelta(days=7*weekofmonth-week)
last_day = date_str[:8]+str(calendar.monthrange(int(date_str[:4]), int(date_str[5:7]))[1])
last_day = datetime.datetime.strptime(last_day, '%Y-%m-%d')
if date_time + delta_start <= date_time:
weekstart=date_time
else:
weekstart=date_time + delta_start
if date_time + delta_end >= last_day:
weekend = last_day
else:
weekend = date_time + delta_end
if weekstart<=last_day:
return weekstart.strftime('%Y-%m-%d'),weekend.strftime('%Y-%m-%d')
def getWeek(beginMonth, endMonth):
weekMonthList=[]
for months in monthRange(beginMonth=beginMonth, endMonth=endMonth):
for weekofmonth in (1,2,3,4,5,6):
weekTulp = days_addsub_forweek(date_str=months+'-01', weekofmonth=weekofmonth)
if weekTulp <> None:
weekMonthList.append((months,weekofmonth,weekTulp[0], weekTulp[1]))
return weekMonthList
# 使用测试
print days_addsub_forweek(date_str='2019-08-01',weekofmonth=5)
for x in getWeek(beginMonth='2019-03', endMonth='2019-06'):
print x[0],x[1],x[2],x[3]
print days_addsub(date_str='2019-01-01',days=5)
print days_addsub(date_str='2019-01-01',days=-5)
展示结果:
/usr/bin/python /Users/nisj/PycharmProjects/BiDataProc/love/xx.py
('2019-08-26', '2019-08-31')
2019-03 1 2019-03-01 2019-03-03
2019-03 2 2019-03-04 2019-03-10
2019-03 3 2019-03-11 2019-03-17
2019-03 4 2019-03-18 2019-03-24
2019-03 5 2019-03-25 2019-03-31
2019-04 1 2019-04-01 2019-04-07
2019-04 2 2019-04-08 2019-04-14
2019-04 3 2019-04-15 2019-04-21
2019-04 4 2019-04-22 2019-04-28
2019-04 5 2019-04-29 2019-04-30
2019-05 1 2019-05-01 2019-05-05
2019-05 2 2019-05-06 2019-05-12
2019-05 3 2019-05-13 2019-05-19
2019-05 4 2019-05-20 2019-05-26
2019-05 5 2019-05-27 2019-05-31
2019-06 1 2019-06-01 2019-06-02
2019-06 2 2019-06-03 2019-06-09
2019-06 3 2019-06-10 2019-06-16
2019-06 4 2019-06-17 2019-06-23
2019-06 5 2019-06-24 2019-06-30
2019-01-06
2018-12-27
Process finished with exit code 0