简体   繁体   中英

How to use striptime '%Y-%m-%d %H:%M:%S' minus - 1 minute.?

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM