سؤال

I have a function, getHoursSince():

def getHoursSince (date):

    prior = datetime.datetime.now() - datetime.timedelta(days=date)

    priorHour = prior.hour

    hoursSinceDate = ...

    return hoursSinceDate

so, I can get a date object, given a constant value, i.e. if yesterday = 1, I can call getHoursSince(yesterday). What I don't know how to do is to get the number of hours between datetime.datetime.now() and the priorHour variable -- any ideas?

هل كانت مفيدة؟

المحلول

You are going about it the wrong way; you just convert the timedelta() to hours:

def getHoursSince(date):
    return int(datetime.timedelta(days=date).total_seconds() // 3600)

which gives:

>>> getHoursSince(1)
24
>>> getHoursSince(1.5)
36
>>> getHoursSince(2)
48
>>> getHoursSince(3)
72

but you can just as well base that off of simple arithmetic:

def getHoursSince(date):
    return int(24 * date)

نصائح أخرى

The timedelta.total_seconds() documentation says:

For interval units other than seconds, use the division form directly (e.g. td / timedelta(microseconds=1)).

Here's what that would look like in this case:

def getHoursSince(date):
    return datetime.timedelta(days=date) // datetime.timedelta(hours=1)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top