find Last mid-night time stamp in python
我想找到最后一个午夜时间戳(只输入当前时间戳)。 什么是最好的方法?
我正在为全球移动应用程序编写python脚本。 具有当前时间戳的用户请求,并且在服务器端,我想找到没有影响时区参数的用户的最后一个午夜时间戳。
我搜索了它,我得到了一个解决方案
1 2 3 | import time etime = int(time.time()) midnight = (etime - (etime % 86400)) + time.altzon |
它对我有用。 但我对
要获得客户端(移动)的午夜时间戳,您需要知道客户端的时区。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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()) |
产量
1 2 3 4 | 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的答案产生的