确定舍入时间范围的时间戳的好方法是什么?例如,我从1388898695的数据库中提取时间戳,转换为“2014-01-04 19:11:35”。
现在假设我想要找到一个过去几分钟的早期记录。所以从2014-01-04 19:10:00开始。我如何找出时间戳的秒数(在本例中为95)并从13388898695中减去它,以便我可以在数据库中搜索19:10:00的时间戳?
我正在寻找一种通用方法,因为我想要计算不同的时间范围,例如5分钟或15分钟。
好的,这不是很漂亮,但是让我们忽略年/月/日滚动,只是试着找到过去的2分钟间隔。所以19:53:12会触发搜索19:52:00(到19:50:00)。
#(2014-01-04 19:53:12)
time1=1388901192
year=int(datetime.datetime.fromtimestamp(time1).strftime('%Y'))
month=int(datetime.datetime.fromtimestamp(time1).strftime('%m'))
day=int(datetime.datetime.fromtimestamp(time1).strftime('%d'))
hours=int(datetime.datetime.fromtimestamp(time1).strftime('%H'))
minutes=int(datetime.datetime.fromtimestamp(time1).strftime('%M'))
seconds=0
if minutes%2 == 0:
minutes-=2
else:
minutes-=1
timeString="%s-%s-%s %s:%s:00" % (year,month,day,hours,minutes)
newTime=time.mktime(time.strptime(timeString, '%Y-%m-%d %H:%M:%S'))
print newTime, time1
print datetime.datetime.fromtimestamp(newTime).strftime('%Y-%m-%d %H:%M:%S')
生成搜索时间 1388901120.0或2014-01-04 19:52:00
这似乎不是一种非常干净的方法。
这是我使用Burhan Khalid方法的通用解决方案:
# 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())
答案 0 :(得分: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)
答案 1 :(得分: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()