首页 > 解决方案 > 如何在 for 循环(if else 语句)中打印数据间隔?Python 问题

问题描述

大家好!我读入了一个 CDF 文件,其中包含在轨卫星的日期、时间、纬度和经度。我正在尝试编写一个 txt 文件,每次卫星悬停在北极站上空时保存数据(我有它的 LAT 和 LON,误差值很小)。

我设法保存了一个具有适当条件的 txt 文件,但是要查看并输出的数据太多了:

2013-01-09 02:05:00 -57.097008 40.165134

2013-01-09 02:06:00 -57.29849 40.504826

2013-01-09 02:07:00 -57.49554 40.834732

2013-01-09 02:08:00 -57.68884 41.154243

2013-01-09 02:09:00 -57.881386 41.45857

等等

几年的数据太多了,无法处理......本质上,我想找到一种方法让代码显示时间间隔。所以不是一分钟一分钟,它更像是:

2013-09-01 02:00:00 ~ 2013-09-01 02:14:00

2013-10-05 04:23:00 ~ 2013-10-05 04:32:00

我使用的代码是:

From spacepy import cdf
import datetime
from numpy import *
import numpy as np

cdf = pycdf.CDF('/directory/file.cdf')
print(cdf)


TIME = cdf['EPOCH']
LAT = cdf['SouthBtrace_GM_LAT']
LON = cdf['SouthBTrace_GM_LON']    

#Loop Count
count = 0
    
with open("example.txt", "a") as testing:
    for i, j in zip(LAT, LON):
        if(-65.26 <= i <= -59.26 and 32.31 <= j <= 52.31):            
            count +=1
            n = count
            testing.write(str(TIME[n-1])+'\t'+str(i)+'\t'+str(j)+ '\n')
               
           
        else:
            count +=1

抱歉,如果我的问题令人困惑。我是编程新手,也从未使用过stackoverflow。

编辑:

>> type(TIME[0])
   datetime.datetime

标签: pythonfor-loopif-statement

解决方案


好吧,我的想法是你添加一个时间参数和一个额外的“if”条件,只有当时间差足够大(10 分钟,15 分钟,或者任何你想要的)时才会满足。所以,比如:

import datetime
delta = datetime.timedelta(seconds = 600) ## the time gap that you want to use
time_one = datetime.datetime(2020,9,16,5,26,0) ## some arbitrary starting value
with open("example.txt", "a") as testing:
    for i, j in zip(LAT, LON):
        if(-65.26 <= i <= -59.26 and 32.31 <= j <= 52.31):
            if TIME > time_one + delta: 
                count +=1
                n = count
                testing.write(str(TIME[n-1])+'\t'+str(i)+'\t'+str(j)+ '\n')
                time_one = TIME  ## resets the time_one value to the new time
        else:
            count +=1

这样,除非时间值比之前写入的条目晚至少 600 秒(假设 EPOCH 值以秒为单位......如果不是,显然使用适当的单位),否则不会将新数据写入 txt 文件。


推荐阅读