什麼是確定舍入時間幀的時間戳的好方法?例如,我從1388898695的數據庫中提取一個時間戳,它轉換爲「2014-01-04 19:11:35」。Python方法找到時間戳差異來計算偶數時間間隔
現在可以說,我想找到這是即使在過去分鐘更早的記錄。所以從2014-01-04 19:10:00開始。我如何從時間戳(本例中爲95)中找出秒數並從13388898695中減去它,以便我可以在數據庫中搜索19:10:00時間戳?
我正在尋找一個通用的方法,因爲我想計算不同時間段,如5的或15的分鐘。
確定這是不是很漂亮,但讓我們忽略年/月/日卷旁白,只是試圖找到過去甚至間隔2分鐘。因此19:53:12會觸發19:52:00(到19:50:00)的搜索。
主要生產的 1388901120.0或2014年1月4日19時52分○○秒
搜索時間看起來這並不是一個非常乾淨的方式來做到這一點。
下面是布爾汗哈立德使用方法我的通用的解決方案:
# take timestamp, rewind to timeframe that provides the newest end point where a full interval
# 10:42:34 -> 10:42:00 for interval=2 to fetch records 10:42:00 to 10:40:00
# 10:49:34 -> 10:40:00 for interval=10 to fetch records 10:40:00 to 10:30:00
dt = datetime.datetime.fromtimestamp(ts)
if (dt.minute % interval) == 0:
prev_ts = dt-datetime.timedelta(minutes=0,seconds=dt.second)
else:
temp=round(dt.minute/interval)
temp*=interval
temp=dt.minute-temp
prev_ts = dt-datetime.timedelta(minutes=temp,seconds=dt.second)
print "%s: %s -> %s" % (interval, dt, prev_ts)
print time.mktime(prev_ts.timetuple())
http://docs.python.org/2/library/datetime.html – SethMMorton
@SethMMorton我希望它似乎很明顯,我使用這些功能,但我有搞清楚如何計算所需的時間,即使問題間隔基於檢索到的時間戳。 – user6972
對不起,這並不明顯。你沒有顯示任何代碼,所以我不知道你在做什麼。你能顯示相關的片段嗎? – SethMMorton