在python中查找最后一个午夜时间戳

2024-10-01 09:18:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我想找到最后一个午夜时间戳(唯一的输入是当前时间戳)。最好的方法是什么?在

我正在为一个全球移动应用程序编写python脚本。用户请求当前的时间戳,在服务器端,我想找到没有影响时区参数的用户的最后一个午夜时间戳。在

我找过了,找到了解决办法

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

这对我很有效。但是我对time.altzon函数感到困惑,它是否会给不同时区的用户带来任何问题。在


Tags: 方法用户import脚本应用程序参数time服务器端
1条回答
网友
1楼 · 发布于 2024-10-01 09:18:18

要获得客户端(移动)的午夜时间戳,您需要知道客户端的时区。在

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())

输出

^{pr2}$

注意:在我的机器上,@phihag's answer产生的1344470400.0与上面的不同(我的机器不在纽约)。在

相关问题 更多 >