How to create a DateTime equal to 15 minutes ago?

后端 未结 9 975
庸人自扰
庸人自扰 2020-12-01 05:56

I need to create a DateTime object that represents the current time minus 15 minutes.

相关标签:
9条回答
  • 2020-12-01 06:15

    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
    
    0 讨论(0)
  • 2020-12-01 06:17

    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.

    0 讨论(0)
  • 2020-12-01 06:19

    only the below code in Python 3.7 worked for me

    from datetime import datetime,timedelta    
    print(datetime.now()-timedelta(seconds=900))
    
    0 讨论(0)
  • 2020-12-01 06:23

    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.

    0 讨论(0)
  • 2020-12-01 06:24

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

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

    0 讨论(0)
  • 2020-12-01 06:28
     datetime.datetime.now() - datetime.timedelta(minutes=15)
    
    0 讨论(0)
提交回复
热议问题