Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
526 views
in Technique[技术] by (71.8m points)

python - What was midnight yesterday as an epoch time?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)):
    # ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...