python进行日期的加减(秒-年)
1)timedelta函数的参数datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)2)日期计算的格式转换【代码块】import datetimedef result(v):print(type(v))print(v)print('\b')# a='202
·
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
3)demo
【代码块】
from dateutil.relativedelta import relativedelta
import datetime,time
today=datetime.datetime.now().strftime("%Y-%m-%d") #[str]2021-09-03
now_timestamp=int(time.time()) #获取现在的时间戳
#获取今天0点的时间戳
today_datetime=time.strptime(today,"%Y-%m-%d")
today_timestamp=int(time.mktime(today_datetime))
#通过开时间时和周期,获取结束时间
"""
end_time=begin_time+relativedelta(months=cycle) #cycle=1,12
"""
def endday(begin_time,cycle):
if isinstance(begin_time,str):
begin_time=datetime.datetime.strptime(begin_time,"%Y-%m-%d")
end_time=(begin_time+relativedelta(months=cycle,days=-1)).strftime("%Y-%m-%d")
return end_time
else:
print("begin_time值需要传入str类型的参数")
begin_time="2021-03-01"
cycle=12
v=endday(begin_time,cycle)
print("合同开始日期%s,合同周期%s"%(begin_time,cycle))
print("合同结束日期%s"%v)
【运行结果】
合同开始日期2021-03-01,合同周期12
合同结束日期2022-02-28
更多推荐
已为社区贡献1条内容
所有评论(0)