2022-08-14 개발일지

컴클로딩·2022년 8월 14일
0

📍 Intro

  • 더미 데이터를 생성하는 과정중에서 다음과 같은 문제점이 발생했다.

    1. Brand 클래스의 name(브랜드명)과 Prodcut클래스의 name(상품명)은 임의로 faker.name()으로 했음. 추후 변경 필요!
      2. Order 클래스의 createdAt도 임의의 날짜 데이터인데 최근 날짜로 변경이 필요
    2. Product 클래스의 가격 범위가 1,000원~10,000,000원인데 범위가 너무 넓어서 수정이 좀 필요하지 않을까 싶음.
  • 해당 문제점들을 각각 해결해보자..!

1. Order 클래스 createdAt 최근 날짜로 변경 필요

🔍 문제점 파악

  • 문제가 되는(?) 코드

        for i in range(1, num + 1):
            user_class = fake.set_user_in_order()
            user_id = user_class.user_id
            product_class = fake.set_product_in_order()
            product_id = product_class.product_id
            amount = fake.pyint(min_value=1, max_value=10)
            product_price = product_class.price
            totalPrice = amount * product_price
            createdAt = fake.iso8601()
    • 위 코드에서 createA에서 fake의 iso8601()메서드를 통해 생성하는데 생성하면 임의의 값이라서 1980년대까 등장한다..그래서 최근 1년 혹은 2년..? 정도의 데이터들만 생성하고 싶은 것이 문제다.
  • faker 패키지 까보기

    def iso8601(
            self,
            tzinfo: Optional[TzInfo] = None,
            end_datetime: Optional[DateParseType] = None,
            sep: str = "T",
            timespec: str = "auto",
        ) -> str:
            """
            Get a timestamp in ISO 8601 format (or one of its profiles).
            :param tzinfo: timezone, instance of datetime.tzinfo subclass
            :param sep: separator between date and time, defaults to 'T'
            :param timespec: format specifier for the time part, defaults to 'auto' - see datetime.isoformat() documentation
            :example: '2003-10-21T16:05:52+0000'
            """
            return self.date_time(tzinfo, end_datetime=end_datetime).isoformat(sep, timespec)
  • date_time 메서드 까보기

    def date_time(
            self,
            tzinfo: Optional[TzInfo] = None,
            end_datetime: Optional[DateParseType] = None,
        ) -> datetime:
            """
            Get a datetime object for a date between January 1, 1970 and now
            :param tzinfo: timezone, instance of datetime.tzinfo subclass
            :example: datetime('2005-08-16 20:39:21')
            :return: datetime
            """
            # NOTE: On windows, the lowest value you can get from windows is 86400
            #       on the first day. Known python issue:
            #       https://bugs.python.org/issue30684
            return datetime(1970, 1, 1, tzinfo=tzinfo) + timedelta(seconds=self.unix_time(end_datetime=end_datetime))
    • 까보니깐 결국 import한 date타임을 사용하고 있었는데 return값을 보아하니 1970-01-01이 시작날짜인 듯하다. 하지만 내부 함수를 내가 못건드리니..다른 함수를 봤는데 date_time_between 함수를 발견했다.
  • date_time_between 사용법

    def date_time_between(
            self,
            start_date: DateParseType = "-30y",
            end_date: DateParseType = "now",
            tzinfo: Optional[TzInfo] = None,
        ) -> datetime:
            """
            Get a datetime object based on a random date between two given dates.
            Accepts date strings that can be recognized by strtotime().
            :param start_date: Defaults to 30 years ago
            :param end_date: Defaults to "now"
            :param tzinfo: timezone, instance of datetime.tzinfo subclass
            :example: datetime('1999-02-02 11:42:52')
            :return: datetime
            """
            start_date = self._parse_date_time(start_date, tzinfo=tzinfo)
            end_date = self._parse_date_time(end_date, tzinfo=tzinfo)
            if end_date - start_date <= 1:
                ts = start_date + self.generator.random.random()
            else:
                ts = self.generator.random.randint(start_date, end_date)
            if tzinfo is None:
                return datetime(1970, 1, 1, tzinfo=tzinfo) + timedelta(seconds=ts)
            else:
                return (datetime(1970, 1, 1, tzinfo=tzutc()) + timedelta(seconds=ts)).astimezone(tzinfo)
    • 파라미터에 String으로 "-30y"를 보니 2년 전부터 지금까지의 날짜를 생성하려면 "-2y"를 하면 되는 것 같다. 그래서 이를 isoformat으로 변경해주면 내가 원하는 값을 얻을 수 있을듯 하다.

❗ 문제 해결

  • 기존 코드를 fake.iso8601()에서 fake.date_time_between(start_date="-2y").isoformat("T", "auto")로 변경해줌으로써 해결!
profile
어떠한 가치를 창출할 수 있을까를 고민하는 개발자. 주로 Spring으로 개발해요. https://comclothing.tistory.com/ 👈🏻티스토리 블로그로 이전 완료

0개의 댓글