計算年、月、日須要安裝組件包python
pip install python-dateutilblog
當前日期時間 import datetime print datetime.datetime.now() # 2018-05-08 16:53:30.101000 格式化時間 import datetime print datetime.datetime.now().strftime("%Y-%m-%d %H:%M") # 2018-05-08 16:54 多加一天 import datetime print (datetime.datetime.now()+datetime.timedelta(days=1)).strftime("%Y-%m-%d %H:%M:%S") # 2018-05-09 16:56:07 減一天 import datetime print (datetime.datetime.now()+datetime.timedelta(days=-1)).strftime("%Y-%m-%d %H:%M:%S") # 2018-05-07 16:56:59 能夠把days改成hours minutes,就能夠提早XX小時/分鐘了。 timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]]) 減去一年 import datetime from dateutil.relativedelta import relativedelta d = datetime.datetime.strptime('20180131', '%Y%m%d') print(d) // 2018-01-31 00:00:00 print((d - relativedelta(years=1)).strftime('%Y%m%d')) // 20170131