0

I am trying to basically use striptime that gives me format of '%Y-%m-%d %H:%M:%S' etc '2019-05-03 09:00:00' and what I am trying to achieve is that I want to take that time - 1 minute so the output should be - 2019-05-03 08:59:00

what I have done so far is

    date_time = '2019-05-03 09:00:00'
    target = datetime.strptime(date_time, '%Y-%m-%d %H:%M:%S')

    now = datetime.now()

    delta = target - now

    if delta > timedelta(0):
        print('Will sleep {} : {}'.format(date_time, delta))
        time.sleep(delta.total_seconds())

and I am not sure how I can make the function to do - 1 minute. I am not sure if its even possible?

Andres123
  • 7
  • 1
  • 7
  • 1
    https://stackoverflow.com/questions/4541629/how-to-create-a-datetime-equal-to-15-minutes-ago – Meow May 02 '19 at 22:44
  • @Meow When I try to do `target(minutes=-1)` i will get an error saying `TypeError: 'datetime.datetime' object is not callable` – Andres123 May 02 '19 at 22:45

2 Answers2

2

It appears you meant to use the formatted datetime variable called target in your if clause but instead you used the string representation of that date called date_time.

Use the datetime object instead and substract timedelta(minutes=1)

Working example:

date_time = '2019-05-03 09:00:00'
target = datetime.strptime(date_time, '%Y-%m-%d %H:%M:%S')

now = datetime.now()

delta = target - now

if delta > timedelta(0):
    target = target - timedelta(minutes=1)
    print('Will sleep {} : {}'.format(target, delta))
    time.sleep(delta.total_seconds())
danny bee
  • 840
  • 6
  • 19
  • I would believe you need to move `target = target - timedelta(minutes=1)` up to between `now = datetime.now` and `delta = target - now` to actually make it start 1 min before the real target time? – Andres123 May 02 '19 at 23:11
  • Yes, if you want to subtract the minute before the if statement evaluation you should definitely do that. – danny bee May 03 '19 at 11:42
  • Thank you! It was exactly what I wanted to do! – Andres123 May 03 '19 at 11:42
0

If you would like to use the current time to determine your output

import datetime, time
from datetime import timedelta

daytime = '2019-05-03 09:00:00'
target = datetime.datetime.strptime(daytime, '%Y-%m-%d %H:%M:%S')
print (datetime.datetime.now())

now = datetime.datetime.now()
new_time = target-now

if  new_time > datetime.timedelta(0):
        print('Will sleep {} : {}'.format(daytime, new_time))
        time.sleep(new_time.total_seconds())
poorpractice
  • 127
  • 10