1.表示一个时间间隔:timedelta

1 from datetime import timedelta
2 a  = timedelta(days=2,hours=6)
3 b = timedelta(hours=4.5)
4 c = a + b

2.表示一个特定的日期:datetime

1 form datetime import datetime,timedelta
2 a = datetime(2019,10,19)
3 b = timedelta(days=2)
4 now = datetime.today()
5 print(now+b)
6 print(a+b)

注:datetime可以正确处理闰年

3.处理有关月份的问题,填补一下datetime的空缺

 from dateutil.relativedelta import relativedelta

1 from dateutil.relativedelta import relativedelta
2 from datetime import datetime
3
4 now = datetime.today()
5 print(now+relativedelta(months=+2)

 4.找出当月的日期范围

1 from datetime import datetime,date,timedelta
2 import calendar
3
4 def get_month_range(start_date=None):
5     if start_date is None:
6         start_date = date.today().replace(day=1)
7         days_in_month = calendar.monthrange(start_date.year,start_date.month)
8         end_date = start_date + timedelta(days = days_in_month)
9     return (start)date,end_date)

5.将字符串转化成日期

1 from datetime import datetime
2 text = "2012-09-20"
3 y = datetime.striptime(text,"%Y-%m-%d")

striptime的性能比较糟糕 如果我们已知时间字符串的格式情况下 建议自己写函数处理

01-03 01:57