python使用datetime模块timedelta实现日期时间相加:
from datetime import datetime
from datetime import timedelta
now = datetime.now()
aDay = timedelta(days=1)
now = now + aDay
print now.strftime('%Y-%m-%d')
from datetime import datetime
from datetime import timedelta
now = datetime.now()
aDay = timedelta(days=-1)
now = now + aDay
print now.strftime('%Y-%m-%d')
写法2:
以下代码通过导入 datetime 模块来获取昨天的日期:
# Filename : test.py # author by : www.runoob.com # 引入 datetime 模块 import datetime def getYesterday(): today=datetime.date.today() oneday=datetime.timedelta(days=1) yesterday=today-oneday return yesterday # 输出 print(getYesterday())
执行以上代码输出结果为:
2015-06-10
以上实例输出的意思为昨天的日期是 2015 年 6 月 10 日。
使用timedelta可以很方便的在日期上做天days,小时hour,分钟,秒,毫秒,微妙的时间计算,如果要计算月份则需要另外的办法
import time
last_month = time.localtime()[1]-1 or 12
print last_month
from datetime import timedelta
from datetime import datetime
import time
d1 = datetime.now()
time.sleep(10)
eclipseTimes = datetime.now() - d1
print eclipseTimes.total_seconds()