代码之家  ›  专栏  ›  技术社区  ›  maximusdooku

如何正确生成带有5分钟时间戳的文件名?

  •  0
  • maximusdooku  · 技术社区  · 10 年前

    我使用下面的代码根据时间步数每隔五分钟生成一次文件名。但它工作不正常。如果您打开precipFileNames,您会看到中间的代码每5分钟停止一次,而是5分钟1秒,这会生成如下文件名:

    E:\MRMS\2004\PRECIPRATE.20040402.051959.tif
    

    我怎样才能正确地做到这一点?

    timeSteps = 417;
    pathstr = 'E:\MRMS\2004';
    startTime = 7.320395312500000e+05;
    peakTime2 = 7.320400104166666e+05;
    precipFileNames=cell(timeSteps,1);
    
    for l = 1:timeSteps
           %precipFileNames{m} = strcat(fileparts(refFile), filesep, datestr(startTime, 'yyyy'), filesep,'PRECIPRATE.',datestr(startTime, 'yyyymmdd.hhMMss'), '.tif');
           precipFileNames{l} = strcat(pathstr(1:end-4), datestr(startTime, 'yyyy'), filesep, 'PRECIPRATE.',datestr(peakTime2, 'yyyymmdd.hhMMss'), '.tif');
           peakTime2 = addtodate(peakTime2, -5, 'minute');  %No. of times we go back in time from peak time
     end
    
    1 回复  |  直到 10 年前
        1
  •  3
  •   Community Mohan Dere    9 年前

    日期/时间使用浮点数进行内部存储。每次循环,您都会添加一个非常小的值(5分钟, 0.0035 )到相对较大的值( 7e05 -ish)这会导致 floating point arithmetic errors 。这些错误表现为与预期值略有不同。

    因为您正在执行此添加(到 peakTime2 )在循环中,一次迭代的浮点误差被放大,因为下一次迭代取决于前一次的结果。

    而不是不断更新 峰值时间2 我会改变 希腊字母表的第4个字母 值并将其应用于 起初的 datetime对象每次通过循环。这样就不会出现累积错误,您只需执行一次减法即可获得特定值。

    for k = 1:timeSteps
        % Compute how many minutes to shift this iteration
        shift = -5 * (k - 1);
    
        % Apply the shift to the reference time
        thistime = addtodate(peakTime2, shift, 'minute');
    
        % Create the filename
        precipFileNames{k} = strcat(pathstr(1:end-4), ...
                                    datestr(startTime, 'yyyy'), ...
                                    filesep, ...
                                    'PRECIPRATE.', ...
                                    datestr(thistime, 'yyyymmdd.hhMMss'), ...
                                    '.tif');
    end
    

    作为补充说明,为了让人们阅读您的代码,我强烈建议您不要使用 l 作为变量,因为它看起来很像 1 .