本文主要是介绍python日期相减(秒、小时、天、月、年),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
python代码
import datetime
today=datetime.datetime.now()
datetime1=today-datetime.timedelta(seconds=10)#减10秒
datetime2=today-datetime.timedelta(minutes=10)#减10分钟
datetime3=today-datetime.timedelta(hours=1)#减1小时
datetime4=today-datetime.timedelta(days=7)#减1天
datetime5=today-datetime.timedelta(weeks=1)#减1周
datetime6=today.strftime('%Y-%m-%d')#将时间格式化为字符串
print('today:',today)
print('second:',datetime1)
print('minute:',datetime2)
print('hour:',datetime3)
print('day:',datetime4)
print('week:',datetime5)
print('时间格式化为字符串:',datetime6)import dateutil.relativedelta
datetime7= datetime.datetime.strptime(datetime6, '%Y-%m-%d')#将字符串格式为时间
datetime8 = datetime7 - dateutil.relativedelta.relativedelta(seconds=10)#减10秒
datetime9 = datetime7 - dateutil.relativedelta.relativedelta(minutes=10)#减10分钟
datetime10 = datetime7 - dateutil.relativedelta.relativedelta(hours=1)#减减1小时
datetime11 = datetime7 - dateutil.relativedelta.relativedelta(days=1)#减1天
datetime12 = datetime7 - dateutil.relativedelta.relativedelta(months=1)#减一个月
datetime13 = datetime7 - dateutil.relativedelta.relativedelta(years=1)#减一年
print('字符串格式为时间:',datetime7)
print('second2:',datetime8)
print('minute2:',datetime9)
print('hour2:',datetime10)
print('day2:',datetime11)
print('month2:',datetime12)
print('year:',datetime13)
运行结果
这篇关于python日期相减(秒、小时、天、月、年)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!