2014-01-05 113 views
0

什麼是確定舍入時間幀的時間戳的好方法?例如,我從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()) 
+1

http://docs.python.org/2/library/datetime.html – SethMMorton

+0

@SethMMorton我希望它似乎很明顯,我使用這些功能,但我有搞清楚如何計算所需的時間,即使問題間隔基於檢索到的時間戳。 – user6972

+0

對不起,這並不明顯。你沒有顯示任何代碼,所以我不知道你在做什麼。你能顯示相關的片段嗎? – SethMMorton

回答

1

下面是一個例子報復分鐘,它應該讓你開始您的其他情況:

>>> import datetime 
>>> ts = 1388898695 
>>> dt = datetime.datetime.fromtimestamp(ts) 
>>> dt.hour,dt.minute,dt.second 
(8, 11, 35) 
>>> next_ts = dt+datetime.timedelta(minutes=1,seconds=-dt.second) 
>>> next_ts.hour,next_ts.minute,next_ts.second 
(8, 12, 0) 
>>> prev_ts = dt-datetime.timedelta(minutes=1,seconds=dt.second) 
>>> prev_ts.hour,prev_ts.minute,prev_ts.second 
(8, 10, 0) 
0

退房http://docs.python.org/3/library/datetime.html#datetime.timedelta

#!/usr/local/cpython-3.3/bin/python 

import time 
import datetime 

def main(): 
    time0 = time.time() 
    time.sleep(3) 
    time1 = time.time() 

    print(datetime.timedelta(seconds=(time1 - time0))) 

main() 
+0

那麼,我將如何採取現有的時間戳(time0)並提取年,月,日,小時,分鐘,秒鐘,以便按照我所希望的時間間隔計算time1? – user6972