使用python获取从昨天0000小时到今天0000小时的unix时间
我需要获得以下值
Today = 6th Feb
time 1 = 5th Feb 0000 hrs
time 2 = 6th Feb 0000 hrs.
所以我有 24 小时的纪元时间。参考是今天,但不是 now()
到目前为止我已经有了这个。
yesterday = datetime.date.today() - datetime.timedelta(days=1)
epoch_yesterday = time.mktime(yesterday.timetuple())
epoch_today = time.mktime(datetime.date.today().timetuple())
两个 epoch_ 值实际上都是从 now() 开始返回秒数,例如 1600 小时(取决于我运行脚本的时间)而不是从 0000/2400 小时开始。我知道最好先获取昨天的纪元时间,然后再添加 24 小时以获得结束日期。但我需要把第一部分做好:),也许我需要睡觉?
ps 抱歉,代码样式不起作用,因此不允许我发布代码样式,并且让我发布此内容非常令人沮丧。
I need to get the following values
Today = 6th Feb
time 1 = 5th Feb 0000 hrs
time 2 = 6th Feb 0000 hrs.
So I have 24 hours in epoch time. The reference is today but not now()
So far I have this.
yesterday = datetime.date.today() - datetime.timedelta(days=1)
epoch_yesterday = time.mktime(yesterday.timetuple())
epoch_today = time.mktime(datetime.date.today().timetuple())
Both epoch_ values are actually returning seconds from now() like 1600 hrs (depends on when I run the script) not from 0000/2400 hrs. I understand it would be better to get yesterdays epoch time and then ad 24 hours to it to get the end date. But I need to get the first part right :) , maybe I need sleep?
p.s. Sorry code styling isn't working, SO won't let me post with code styling and was very frustrating to get SO to post this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
更简单的方法可能是显式构造日期,如下所示:
这将为您提供刚刚过去的午夜的时间戳。正如您所知,
time.mktime
将为您提供纪元值。只需添加或减去 24 * 60 * 60 即可获得前一个或下一个午夜。哦!请注意,纪元值将是从 1970 年 1 月 1 日 UTC 午夜开始的秒数。如果您需要所在时区午夜后的几秒,请记住进行相应调整!
更新:测试代码,在太平洋标准时间下午 1 点之前从 shell 执行:
注意:time_at_start_of_today_local 是 1970 年 1 月 1 日午夜与当天开始之间的秒数您的时区。如果您想要以 UTC 表示的当天开始的秒数,请从 time_at_start_of_today_local 中减去您的时区:
请注意,您在这里进入了奇怪的领域,特别是您关心哪一天?如果当前您所在时区是星期二,但 UTC 时间仍然是星期一,那么您认为今天的午夜是哪个午夜?
The simpler way might be to construct the date explicitly as so:
That gets you the timestamp for the just passed midnight. As you already know
time.mktime
will get you your the epoch value. Just add or subtract 24 * 60 * 60 to get the previous or next midnight from there.Oh! And be aware that the epochal value will be seconds from midnight 1970, Jan 1st UTC. If you need seconds from midnight in your timezone, remember to adjust accordingly!
Update: test code, executed from the shell at just before 1 pm, PST:
Note: time_at_start_of_today_local is the number of seconds between 1970 Jan 1st, midnight, and the start of the current day in your timezone. If you want the number of seconds to the start of the current day in UTC, then subtract your time zone from time_at_start_of_today_local:
Be aware that you get into odd territory here, specifically who's day do you care about? If it's currently Tuesday in your timezone, but still Monday in UTC, which midnight do you consider today's midnight for your purposes?