-2

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

deceze
  • 510,633
  • 85
  • 743
  • 889
Deoj
  • 71
  • 1
  • 5
  • 2
    Can you decombobulate that a bit more, so we don't need to twist our brains quite as much to grok what's going on here and what you want to achieve…? – deceze Aug 19 '21 at 13:36
  • `minutes =(now.minute - (now.minute - (now.minute % 5)))` in t0 can also be coded as `minutes =now.minute % 5` and that's where you confused yourself with math for t0 and t1 – Chirag Jain Aug 19 '21 at 13:52

1 Answers1

1

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)

Giordano
  • 5,422
  • 3
  • 33
  • 49