昨天午夜是什么时代? [英] What was midnight yesterday as an epoch time?

查看:135
本文介绍了昨天午夜是什么时代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让我的头脑围绕datetime模块。我知道现在的时间是一个时代,一个事件发生的时间(作为一个时代)。我需要做的是弄清楚这个事件是否在昨天午夜到午夜之间发生。

  t = time.time() #现在是
t2 = 1234567890#从我的日志中的某些任意时间

24小时前是t - 86400,但是我怎么能把它上下颠倒到午夜。我遇到了一个方法来获取时间戳进出日期时间,然后操纵datetime来设置时间。

解决方案

p>生成最后一个午夜很容易:

  from datetime import datetime,date,time 

午夜= datetime.combine(date.today(),time.min)

结合了今天的日期,一起 time.min 在午夜时间形成 datetime 对象。



使用 timedelta()您可以计算以前的 午夜:

  from datetime import timedelta 

yesterday_midnight =午夜 - timedelta(days = 1)

现在你需要做的是测试你的时间戳记是否在这两点之间:

  timestamp = datetime.fromtimestamp(some_timestamp_from_y my_log)
if yesterday_midnight< = timestamp<午夜:
#这发生在00:00:00和23:59:59之间

组合成一个函数:

  from datetime import datetime,date,time,timedelta 

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


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.

解决方案

Generating the last midnight is easy:

from datetime import datetime, date, time

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

That combines today's date, together with time.min to form a datetime object at midnight.

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

from datetime import timedelta

yesterday_midnight = midnight - timedelta(days=1)

Now all you need to do is 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

Combined into one function:

from datetime import datetime, date, time, timedelta

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

这篇关于昨天午夜是什么时代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆