Notice
Recent Posts
Recent Comments
Link
«   2026/04   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30
Tags
more
Archives
Today
Total
관리 메뉴

인턴기록지

dt_ewl_history_load.py 코드 설명 본문

Python

dt_ewl_history_load.py 코드 설명

인턴신분현경이 2020. 12. 8. 17:21

get_pulltime()

 

DB Table 'ewl_pulllog'가 

이런식으로 데이터가 들어있다면 get_pulltime()함수를 이용해 각 파일명별 pull_time을 리턴해준다.

저번에 듣기론 서버에서 데이터를 가져올 때 매달 새벽 1시라고 들어서 저렇게 설정해 주었다.

# get pull_time from ewl_pulllog
def get_pulltime(database, file_name):
    """ 각 파일에 해당하는 ewl_pulllog 테이블의 pull_time을 가져온다.

    :param database: Postgresql Info
    :param str file_name: File Name
    :return: 
        "%Y-%m-%d %H:%M:%S" 식으로 바꿔준 해당 데이터 파일을 서버에서 가져온 시간

    Variables:
    ----------
    pull_time : ewl_pulllog에서 가져온 가장 최근에 파일을 pull한 시간

    """
    try:
        # connect DB
        conn = psycopg2.connect(**database)
        cursor = conn.cursor()

        # Get pull time by filename
        # pull_time을 내림차순으로 limit 1 걸어주면 제일 최근 pull한 시각이 나옴
        if file_name.find('repair') >= 0:
            pull_query = """SELECT pull_time FROM ewl_pulllog
                            where file_name like 'ewl_repair%'
                            order by pull_time desc limit 1;"""
            cursor.execute(pull_query)
        elif file_name.find('replacing') >= 0:
            pull_query = """SELECT pull_time FROM ewl_pulllog
                            where file_name like 'ewl_replacing%'
                            order by pull_time desc limit 1;"""
            cursor.execute(pull_query)
        elif file_name.find('rental_') >= 0:
            pull_query = """SELECT pull_time FROM ewl_pulllog
                            where file_name like 'ewl_rental_%'
                            order by pull_time desc limit 1;"""
            cursor.execute(pull_query)

        pull_time = cursor.fetchall()
        pull_time = datetime.datetime.strptime(str(pull_time[0][0]),
                                                "%Y-%m-%d %H:%M:%S")

        return pull_time

    except psycopg2.DatabaseError as error:
        logger.error(f"get_pulltime() {error}")

    finally:
        if conn is not None:
            conn.close()

load_new_repair_data()

ex) pull_time이 08/01 01시라면 08/01일 부터의 수리기록을 가져온다.

# Extracting new repair data
def load_new_repair_data(direc, file_name, time_value):
    """ 서버에서 가져온 수리내역 데이터에서 pull_time기준으로 
    그 이후에 새로 추가된 데이터를 뽑는다.

    :param directory direc: current directory path
    :param str file_name: File Name
    :param time time_value: get_pulltime 함수에서 받아온 수리내역의 최근 pull_time
    :return: 새로 추가된 수리내역 데이터

    """
    #database.ini 파일의 folder의 경로의 파일
    filepath = os.path.join(direc.get('folder'), file_name)

    try:
        datafile = open(filepath, mode='r', encoding='utf-8')
        csv_reader = csv.reader(datafile)
        data_rows = list(csv_reader)

        # get time column index
        out_time_column_index = data_rows[0].index("등록_일시")
        in_time_column_index = data_rows[0].index("완료_일시")

        # remove header
        columns = data_rows.pop(0)
        logger.debug("pull_time is {}".format(time_value))
		
        # 새로 추가된 데이터를 넣는 리스트
        update_data_rows = []
        # append columns
        update_data_rows.append(columns)

        # data_time vs pull_time
        for row in data_rows:
        	# 수리하기위해 자전거를 뺀 시간
            out_time = row[out_time_column_index]
            # 수리 후 자전거를 정류소에 넣은 시간
            in_time = row[in_time_column_index]
            # 시간이 없으니 날짜로만 비교해주기 위해 pull_time '일'까지 잘라줌
            vs_time = datetime.datetime(time_value.year, time_value.month, 
                                        time_value.day, 00, 00, 00)
            # out data o in data o
            if out_time != '' and in_time != '':
                # 분리시간 >= pull_time 인 경우
                if datetime.datetime.strptime(out_time,
                                                    "%Y-%m-%d") >= vs_time :
                    update_data_rows.append(row)
            # out data o in data x
            elif out_time != '' and in_time == '':
                # 분리시간 >= pull_time
                if datetime.datetime.strptime(out_time,
                                                    "%Y-%m-%d") >= vs_time:
                    update_data_rows.append(row)
            else:   #except data
                logger.error(f"Repair Data is out of range {row}")
                sys.exit()

        """ append 된 데이터 txt로 write / 확인용으로 넣어둔 것! 최종에선 이코드 지우기
        new_file = open(os.path.join(direc.get('folder'),
                    'repair_new_data.txt'), mode='at', encoding='UTF-8')
        for row in update_data_rows:
            for ix in range(len(row)):
                if ix == len(row)-1:
                    new_file.write(row[ix])
                else:
                    # write defect part
                    if ix == 4 :
                        new_file.write('"')
                        new_file.writelines(row[ix])
                        new_file.write('"')
                        new_file.write(',')
                    else:
                        new_file.write(row[ix])
                        new_file.write(',')
            new_file.write('\n')
        new_file.close()
		"""
        
        datafile.close()
        logger.info(f"Repair pull_appended_data \
                    {len(update_data_rows)-1} rows finish")

        return update_data_rows

    except psycopg2.DatabaseError as error:
        logger.error(f"load_new_repair_data() {error}")

load_new_replacing_data() & load_new_rental_data()

위의 load_new_repair_data()