3

So I need to calculate 20 minutes before the last 10 mins. EG if it's currently 13:07, the time I need is 12:40

So from my research, I think I need to find the last 10th (or 0th) minute of the hour, then minus 20 minutes from that.

I found an answer to finding the next 10th minute

so I adjusted the code to find the last 10th minute, and then simply "- datetime.timedelta(minutes=20)"

import math
from datetime import datetime, timedelta

def ceil_dt(dt, delta):
    return datetime.min + math.ceil((dt - datetime.min) / delta) * delta

print(ceil_dt(datetime(2012, 10, 25, 17, 2, 16), timedelta(minutes=-10))) - datetime.timedelta(minutes=20)

But it gives me the following exception

2012-10-25 17:00:00
Traceback (most recent call last):
  File "F:/Pythong/test", line 7, in <module>
    print(ceil_dt(datetime(2012, 10, 25, 17, 2, 16), timedelta(minutes=-10))) - datetime.timedelta(minutes=20)
AttributeError: type object 'datetime.datetime' has no attribute 'timedelta'

What I am doing wrong?

jpp
  • 159,742
  • 34
  • 281
  • 339
Paul Zet
  • 71
  • 8

2 Answers2

1

There are 2 issues with your code. First, you import timedelta and then call datetime.timedelta, when you should call timedelta directly. Second, your close parenthesis for print is misplaced. So this will work:

ceil_dt(datetime(2012, 10, 25, 17, 2, 16), timedelta(minutes=-10)) - timedelta(minutes=20)

But you can just use:

dt = datetime(2012, 10, 25, 17, 2, 16)
res = dt - timedelta(minutes=dt.minute+20)
jpp
  • 159,742
  • 34
  • 281
  • 339
1

The import problem is with datetime.timedelta. As you import like from datetime import datetime, timedelta, so datetime in the following code is actually datetime.datetime class.

There're two solutions: either you change datetime.timedelta to timedelta, or you change the way you import to import datetime and then change datetime in your code to datetime.datetime. I'd recommend the first one as it is simpler.

The fact that datetime package and datetime class have the same name is making things a bit complicated. You need to be careful and know exactly which is which.

Kevin Fang
  • 1,966
  • 2
  • 16
  • 31