python 时间处理之月份加减问题
作者:平头哥(AdgerZhou)
这篇文章主要介绍了python 时间处理之月份加减问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
python时间处理月份加减
第三方模块 :
python-dateutil
安装方式:
pip install python-dateutil
实例代码:
import datetime from dateutil.relativedelta import relativedelta datetime_now = datetime.datetime.now() datetime_three_month_ago = datetime_now - relativedelta(months=3) print datetime_three_month_ago
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)
运行结果
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。