Answer a question

I'm trying to get my head around the datetime module. I know the time now as an epoch and the time an event last happened (as an epoch time). What I need to do is figure out whether that event happened between midnight and midnight of yesterday.

t = time.time() # is now
t2 = 1234567890 # some arbitrary time from my log

24 hours ago is t - 86400, but how can I round that up and down to midnight. I'm having real trouble finding a way to get timestamps in and out of datetime or then manipulating a datetime to set the time.

Answers

In the Middle of the Night

Generating the last midnight is easy:

from datetime import datetime, time

midnight = datetime.combine(datetime.today(), time.min)

That combines today's date (you can use date() or a datetime() instance, your pick), together with time.min to form a datetime object at midnight.

Yesterday

With a timedelta() you can calculate the previous midnight:

from datetime import timedelta

yesterday_midnight = midnight - timedelta(days=1)

That Was Yesterday

Now test if your timestamp is in between these two points:

timestamp = datetime.fromtimestamp(some_timestamp_from_your_log)
if yesterday_midnight <= timestamp < midnight:
    # this happened between 00:00:00 and 23:59:59 yesterday

All Together Now

Combined into one function:

from datetime import datetime, time, timedelta

def is_yesterday(timestamp):
    midnight = datetime.combine(datetime.today(), time.min)
    yesterday_midnight = midnight - timedelta(days=1)
    return yesterday_midnight <= timestamp < midnight:

if is_yesterday(datetime.fromtimestamp(some_timestamp_from_your_log)):
    # ...
Logo

学AI,认准AI Studio!GPU算力,限时免费领,邀请好友解锁更多惊喜福利 >>>

更多推荐