如何创build一个等于15分钟前的DateTime?

我需要创build一个DateTime对象,表示当前时间减去15分钟。

导入date时间,然后魔法timedelta的东西:

In [63]: datetime.datetime.now() Out[63]: datetime.datetime(2010, 12, 27, 14, 39, 19, 700401) In [64]: datetime.datetime.now() - datetime.timedelta(minutes=15) Out[64]: datetime.datetime(2010, 12, 27, 14, 24, 21, 684435) 
  datetime.datetime.now() - datetime.timedelta(minutes=15) 

除了timedelta对象http://docs.python.org/library/datetime.html之外,还使用DateTime

datetime.datetime.now()-datetime.timedelta(minutes=15)

 from datetime import timedelta datetime.datetime.now() - datetime.timedelta(0, 900) Actually 900 is in seconds. Which is equal to 15 minutes. `15*60 = 900` 

如果你想看更多的例子,我已经提供了两种方法来分钟以及几年和几小时:

 import datetime print(datetime.datetime.now()) print(datetime.datetime.now() - datetime.timedelta(minutes = 15)) print(datetime.datetime.now() + datetime.timedelta(minutes = -15)) print(datetime.timedelta(hours = 5)) print(datetime.datetime.now() + datetime.timedelta(days = 3)) print(datetime.datetime.now() + datetime.timedelta(days = -9)) print(datetime.datetime.now() - datetime.timedelta(days = 9)) 

我得到以下结果:

 2016-06-03 16:04:03.706615 2016-06-03 15:49:03.706622 2016-06-03 15:49:03.706642 5:00:00 2016-06-06 16:04:03.706665 2016-05-25 16:04:03.706676 2016-05-25 16:04:03.706687 2016-06-03 16:04:03.706716 

这只是做什么:

 datetime.datetime.now() - datetime.timedelta(minutes = 15) 

timedelta是专门devise用来减less或增加datetime的差异(差异)。

datetime.datetime.now() - datetime.timedelta(0, 15 * 60)

timedelta是一个“时间的变化”。 第二个参数中的第一个参数和第二个参数需要几天时间。 15 * 60秒是15分钟。