开发者

How to create a DateTime equal to 15 minutes ago?

开发者 https://www.devze.com 2023-02-01 03:31 出处:网络
I need to create a DateTime object that represents开发者_JAVA百科 the current time minus 15 minutes.import datetime and then the magic timedelta stuff:

I need to create a DateTime object that represents开发者_JAVA百科 the current time minus 15 minutes.


import datetime and then the magic timedelta stuff:

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)


This is simply what to do:

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

timedeltas are specifically designed to allow you to subtract or add deltas (differences) to datetimes.


import datetime 
datetime.datetime.now() - datetime.timedelta(0, 900)

Actually 900 is in seconds. Which is equal to 15 minutes. `15*60 = 900`


I have provide two methods for doing so for minutes as well as for years and hours if you want to see more examples:

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))

I get the following results:

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


Use DateTime in addition to a timedelta object http://docs.python.org/library/datetime.html

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


only the below code in Python 3.7 worked for me

from datetime import datetime,timedelta    
print(datetime.now()-timedelta(seconds=900))


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

timedelta is a "change in time". It takes days as the first parameter and seconds in the second parameter. 15 * 60 seconds is 15 minutes.


If you are using time.time() and wants timestamp as output

Simply use

CONSTANT_SECONDS = 900 # time  in seconds (900 seconds = 15 min)

current_time = int(time.time())
time_before_15_min = current_time - CONSTANT_SECONDS

You can change 900 seconds as per your required time.

0

精彩评论

暂无评论...
验证码 换一张
取 消