在Python中查找上一个午夜时间戳

3

我希望找到上一个午夜时间戳(只有当前时间戳作为输入)。有什么最好的方法?

我正在编写全球移动应用程序的Python脚本。用户请求包含当前时间戳,在服务器端,我想找到用户上一次午夜的时间戳,不影响时区参数。

我搜索了一下,找到了一种解决方案。

import time
etime = int(time.time())
midnight = (etime - (etime % 86400)) + time.altzon

这对我来说有效。但是我对 time.altzon 函数感到困惑,它是否会影响不同时区的用户。


如何获取给定时区的“午夜”UTC时间? - jfs
1个回答

5
要获取客户端(移动设备)的午夜时间戳,您需要了解客户端的时区。
from datetime import datetime
import pytz # pip install pytz

fmt = '%Y-%m-%d %H:%M:%S %Z%z'
tz = pytz.timezone("America/New_York") # supply client's timezone here

# Get correct date for the midnight using given timezone.

# due to we are interested only in midnight we can:

# 1. ignore ambiguity when local time repeats itself during DST change e.g.,
# 2012-04-01 02:30:00 EST+1100 and
# 2012-04-01 02:30:00 EST+1000
# otherwise we should have started with UTC time

# 2. rely on .now(tz) to choose timezone correctly (dst/no dst)
now = datetime.now(tz)
print(now.strftime(fmt))

# Get midnight in the correct timezone (taking into account DST)
midnight = tz.localize(now.replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=None),
                       is_dst=None)
print(midnight.strftime(fmt))

# Convert to UTC (no need to call `tz.normalize()` due to UTC has no DST transitions)
dt = midnight.astimezone(pytz.utc)
print(dt.strftime(fmt))

# Get POSIX timestamp
print((dt - datetime(1970,1,1, tzinfo=pytz.utc)).total_seconds())

输出

2012-08-09 08:46:29 EDT-0400
2012-08-09 00:00:00 EDT-0400
2012-08-09 04:00:00 UTC+0000
1344484800.0

注意:在我的机器上@phihag的答案生成的是1344470400.0,与上面的结果不同(我的机器不在纽约)。

@ J.F. Sebastian 我得到了客户端时间戳作为URL参数,使用该时间戳我将找到昨晚的最后一个时间戳。 - Jisson
@Jisson:如果你不知道客户端的时区,怎么知道什么时间是午夜?现在地球上某个地方肯定是午夜。 - jfs
@J.F.Sebastian 嗯,他可能想要记录一些每日统计数据(类似于 stackoverflow 上的今天声望,如果我没记错的话)。哦,还有为什么你在这里使用 print 作为语句?只需包括括号,这在 Python 3 上也可以正常工作。 - phihag
@ J.F. Sebastian,我不是一个专业的程序员。我能使用以下算法找到午夜时间戳吗?t = 获取参数时间戳的日期时间;午夜 = t.replace(hour=0, minute=0, second=0, microsecond=0)? - Jisson
@Jisson:.replace() 只有在相应的日期时间对象具有正确的客户端时区时才起作用。所以问题是,是否可以在给定 POSIX 时间戳的情况下获取具有正确时区的日期时间对象?(我猜你不能) - jfs
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接