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

在python中查找最后一个午夜时间戳,python,python-2.7,Python,Python 2.7,我想找到最后一个午夜时间戳(唯一的输入是当前时间戳)。最好的方法是什么 我正在为一个全球移动应用程序编写python脚本。用户请求带有当前时间戳,在服务器端我想找到用户的最后一个午夜时间戳,不带out-affect时区参数 我找到了答案 import time etime = int(time.time()) midnight = (etime - (etime % 86400)) + time.altzon 这对我有用。但是我对时间感到困惑。altzon功能是否会给不同时区的用户带来任何问题

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

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

我找到了答案

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

这对我有用。但是我对时间感到困惑。altzon功能是否会给不同时区的用户带来任何问题。

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

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())
输出
注意:在我的机器上产生的
1344470400.0
与上述内容不同(我的机器不在纽约)。

相关:@J.F.Sebastian我得到了客户端时间戳作为url参数,使用该时间戳我将查找最后一个午夜timestamp@Jisson:在不知道客户时区的情况下,如何知道午夜是几点?现在是地球上某个地方的午夜。@J.F.Sebastian Umm,他可能想记录一些每日统计数据(如果我没有弄错的话,类似于stackoverflow今天的声誉)。哦,那你为什么在这里用
print
作为语句呢?只要加上括号,在Python3上也可以正常工作。@phihag:OP明确地说:“我想获取客户端(移动)的午夜时间戳。”。这个问题有标签
python-2.7
,所以
print
不是一个函数。@J.F.Sebastian,我不是一个专业的程序员。我能用下面的算法t=datetimeof get参数timestamp;midnight=t.replace(小时=0,分钟=0,秒=0,微秒=0)找到午夜时间戳吗?
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