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

如何在python panda中检查特定范围内的日期时间列?

  •  0
  • Ratha  · 技术社区  · 6 年前

    该特定文件中的所有行将延迟一分钟。(这是所有读数,因此间隔不超过一分钟)

    使用panda,我加载日期列,如下所示;

    def read_dipsfile(writer):
        atg_path = '/Users/ratha/PycharmProjects/DataLoader/data/dips'
        files = os.listdir(atg_path)
        df = pd.DataFrame()
        dateCol = ['Dip Time']
        for f in files:
            if(f.endswith('.CSV')):
                data = pd.read_csv(os.path.join(atg_path, f), delimiter=',', skiprows=[1], skipinitialspace=True,
                                   parse_dates=dateCol)
    
                if mid_day_check(data['Dip Time']):  --< gives error
                    df = df.append(data)
    
    
    def mid_day_check(startTime):
        midnightTime = datetime.datetime.strptime(startTime, '%Y%m%d')
        hourbefore = datetime.datetime.strptime(startTime, '%Y%m%d') + datetime.timedelta(hours=-1)
    
        if startTime <= midnightTime and startTime>=hourbefore:
            return True
        else:
            return False
    

    在上面的代码中,如何将列传递给函数?

        midnightTime = datetime.datetime.strptime(startTime, '%Y%m%d')
    TypeError: strptime() argument 1 must be str, not Series
    

    0 回复  |  直到 6 年前
        1
  •  2
  •   jezrael    6 年前

    我认为你需要:

    def mid_day_check(startTime):
        #remove times
        midnightTime = startTime.dt.normalize()
        #add timedelta
        hourbefore = midnightTime + pd.Timedelta(hours=-1)
    
        #test with between and return at least one True by any
        return startTime.between(hourbefore, midnightTime).any()
    
        2
  •  1
  •   Prateek Jha    6 年前

    看来你想通过pd系列考试 strptime() 这是无效的。 pd.to_datetime() 方法来实现相同的功能。

    pd.to_datetime(data['Dip Time'], format='%b %d, %Y')
    

    请查看这些链接以获取解释。

    1. strptime
    2. conversion from series