Search code examples
pythonpython-3.xdatetimepython-datetimetimedelta

reduce 5 minutes from time using timedelta


Want to print time less than 5 mins after calculating time:

now = datetime(2020,11,9,13,38,18)


t0 = datetime.strptime((now - timedelta(minutes =(now.minute - (now.minute - (now.minute % 5))), seconds = now.second)).strftime("%Y-%m-%d %H:%M:%S"),"%Y-%m-%d %H:%M:%S") #getting the time in multiples of 5 i.e 13:35:00
t1 = (t0 - timedelta(minutes = (t0.minute - 5))) #reducing 5 mins i.e 13:30:00
print(t0)
print(t1)

t0 gives the result as expected but t1 printed 13:05:00, but it should be 13:30:00


Solution

  • If I understood correctly your question you can just do like this:

    now = datetime(2020,11,9,13,38,18)
    t0 = datetime.strptime((now - timedelta(minutes =(now.minute - (now.minute - (now.minute % 5))), seconds = now.second)).strftime("%Y-%m-%d %H:%M:%S"),"%Y-%m-%d %H:%M:%S") #getting the time in multiples of 5 i.e 13:35:00
    t1 = t0 - timedelta(minutes=5)
    print(t1)
    >>> datetime.datetime(2020, 11, 9, 13, 30)
    

    Basically if you want "remove" 5 minutes from a datetime object you can use timedelta passing the amount of minutes as parameter (5 in this case).

    The result is another datetime object. If you want you can format it as string as you prefer.

    Your code is wrong because in that way you are "removing" 25 minutes (t0.minute = 30 - 5)