1)使用datetime模块进行日期的加减
timedelta函数:参数不包含“年”、“月”?
【代码块】
"""
datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
"""
import datetime
def result(v):
print(type(v))
print(v)
print('\b')
# a='2021-09-01' #给定一个开始日期
a=datetime.datetime.now()
a=a.strftime("%Y-%m-%d") #获取当前日期
result(a)
#将str格式的日期,解析为元祖格式,用于日期计算
b = datetime.datetime.strptime(a, "%Y-%m-%d")
result(b)
#日期做加减法
c=b-datetime.timedelta(days=10)
result(c)
#将datetime格式转换为str
d=c.strftime("%Y-%m-%d")
result(d)
【运行结果】
<class 'str'> 2021-09-01
<class 'datetime.datetime'> 2021-09-01 00:00:00
<class 'datetime.datetime'> 2021-08-22 00:00:00
<class 'str'> 2021-08-22
2)使用relativedelta函数,对日期进行加减
要使用relativedelta函数,需要先安装dateutil库。
【代码块】
"""
def __init__(self, dt1=None, dt2=None,
years=0, months=0, days=0, leapdays=0, weeks=0,
hours=0, minutes=0, seconds=0, microseconds=0,
year=None, month=None, day=None, weekday=None,
yearday=None, nlyearday=None,
hour=None, minute=None, second=None, microsecond=None)
"""
from dateutil.relativedelta import relativedelta
import datetime
def result(v):
print(type(v))
print(v)
print('\b')
dt = '2021-9-2'
dt=datetime.datetime.strptime(dt,'%Y-%m-%d')
result(dt)
delta = dt + relativedelta(years=1)
result(datetime)
delta2 = delta.strftime('%Y-%m-%d')
result(delta2)
【运行结果】
<class 'datetime.datetime'> 2021-09-02 00:00:00
<class 'module'> <module 'datetime' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/datetime.py'>
<class 'str'> 2022-09-02
|