from datetime import datetime, timedelta, date '''今天''' today1 = date.today() # 精确到`天` today2 = datetime.today() # 精确到`微秒` str(today1), str(today2) # 结果: # datetime.date(2015, 11, 20) # datetime.datetime(2015, 11, 20, 16, 26, 21, 593990) # ('2015-11-20', '2015-11-20 16:26:21.593990) '''昨天''' yesterday1 = date.today() + timedelta(days=-1) yesterday2 = datetime.today() + timedelta(days=-1) str(yesterday1), str(yesterday2) # 结果: # datetime.date(2015, 11, 19) # datetime.datetime(2015, 11, 19, 16, 26, 21, 593990) # ('2015-11-19', '2015-11-19 16:26:21.593990) '''明天''' tomorrow1 = date.today() + timedelta(days=1) tomorrow2 = datetime.today() + timedelta(days=1) str(tomorrow1), str(tomorrow2) # 结果: # datetime.date(2015, 11, 21) # datetime.datetime(2015, 11, 21, 16, 26, 21, 593990) # ('2015-11-21', '2015-11-21 16:26:21.593990)
那获取几小时,几分钟,甚至几秒钟先后的时间呢?该怎么获取?python
看以下的代码:git
from datetime import datetime, timedelta # 获取两小时前的时间 date_time = datetime.today() + timedelta(hours=-2)
其实就是给 timedelta()
这个类传入的参数变一下就能够了github
可传入的参数有 timedelta(weeks, days, hours, second, milliseconds, microseconds)
每一个参数都是可选参数,默认值为0,参数值必须是这些(整数
,浮点数
,正数
,负数
)函数
分别表示:timedelta(周,日,时,分,秒,毫秒,微秒)
。也只能传入这7个参数code
说明:timedelta 这个对象实际上是用来表示两个时间的间隔对象
上面咱们都是使用 datetime.today() 加上 timedelta()
,那若是是 datetime.today() 减去 timedelta()
这样呢? 其实得出结果就是相反而已,不明白能够动手试一下,对比一下 +
或 -
以后的结果。get
由于 timedelta()
这个对象传入的参数最大日期时间单位是周
,最小的是 微秒
,
因此,关于 年
和 月
须要咱们手动处理一下it
import datetime import calendar def conver(value, years=0, months=0): if months: more_years, months = divmod(months, 12) years += more_years if not (1 <= months + value.month <= 12): more_years, months = divmod(months + value.month, 12) months -= value.month years += more_years if months or years: year = value.year + years month = value.month + months # 此月份的的天号不存在转换后的月份里,将引起一个 ValueError 异常 # 好比,1月份有31天,2月份有29天,我须要1月31号的后一个月的日期,也就是2月31号,可是2月份没有31号 # 因此会引起一个 ValueError 异常 # 下面这个异常处理就是为了解决这个问题的 try: value = value.replace(year=year, month=month) except ValueError: _, destination_days = calendar.monthrange(year, month) day = value.day - destination_days month += 1 if month > 12: month = 1 year += 1 value = value.replace(year=year, month=month, day=day) return value today = datetime.datetime.today() print today # 今天日期 print conver(today, months=1) # 1月后 print conver(today, months=-1) # 1月前 print conver(today, years=1) # 1年后 # 结果 # datetime.datetime(2015, 11, 20, 16, 26, 21, 593990) # datetime.datetime(2015, 12, 20, 16, 26, 21, 593990) # datetime.datetime(2015, 10, 20, 16, 26, 21, 593990) # datetime.datetime(2016, 11, 20, 16, 26, 21, 593990)
代码取自 when.py 的
_add_time
函数部分代码io