datetime及其加减
from dateutil.relativedelta import relativedelta from datetime import date, timedelta import datetime
打印当前时间
In [51]: datetime.datetime.now()
Out[51]: datetime.datetime(2017, 7, 19, 10, 42, 45, 125701)
In [54]: datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
Out[54]: '2017-07-19 10:43:33'
打印当前日期
In [49]: datetime.date.today()
Out[49]: datetime.date(2017, 7, 19)
打印指定时间并格式化
In [32]: datetime.date(2017,11,1)
Out[32]: datetime.date(2017, 11, 1)
d3 = datetime.datetime(2017,1,2,3,4,5)
In [43]: d3.strftime("%Y-%m-%d %H:%M:%S") Out[43]: '2017-01-02 03:04:05'
对时间进行加减(注意timedelta与relativedelta的区别)
In [58]: d3 + datetime.timedelta(days=-1)
Out[58]: datetime.datetime(2017, 1, 1, 3, 4, 5)
In [44]: d3 + relativedelta(days=1)
Out[44]: datetime.datetime(2017, 1, 3, 3, 4, 5)
In [45]: d3 + relativedelta(month=2)
Out[45]: datetime.datetime(2017, 2, 2, 3, 4, 5)
In [46]: d3 + relativedelta(months=2)
Out[46]: datetime.datetime(2017, 3, 2, 3, 4, 5)
In [47]: d3 + relativedelta(minutes=2)
Out[47]: datetime.datetime(2017, 1, 2, 3, 6, 5)