我需要创建一个DateTime对象,表示当前时间减去15分钟。
答案 0 :(得分:190)
导入日期时间,然后是魔术时间点:
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)
答案 1 :(得分:30)
datetime.datetime.now() - datetime.timedelta(minutes=15)
答案 2 :(得分:9)
这只是做什么:
datetime.datetime.now() - datetime.timedelta(minutes = 15)
答案 3 :(得分:8)
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`
答案 4 :(得分:7)
除timedelta
对象外,还使用DateTime
http://docs.python.org/library/datetime.html
datetime.datetime.now()-datetime.timedelta(minutes=15)
答案 5 :(得分:6)
如果您想查看更多示例,我提供了两种方法,分钟以及数年和数小时:
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
答案 6 :(得分:4)
datetime.datetime.now() - datetime.timedelta(0, 15 * 60)
timedelta
是“时间的变化”。第一个参数需要几天,第二个参数需要几秒。 15 * 60
秒是15分钟。
答案 7 :(得分:3)
只有下面的Python 3.7代码对我有用
from datetime import datetime,timedelta
print(datetime.now()-timedelta(seconds=900))
答案 8 :(得分:0)
如果您使用time.time()
,并且希望将时间戳记作为输出
只需使用
CONSTANT_SECONDS = 900 # time in seconds (900 seconds = 15 min)
current_time = int(time.time())
time_before_15_min = current_time - CONSTANT_SECONDS
您可以根据需要更改900秒。