두 시점을 받아서 지정된 기간을 나열하는 파이썬 프로그램
개발관련/Python :
2021. 3. 21. 21:11
두 시점의 'YYYYMM', 형식의 날짜를 받아서
interval만큼씩 잘라서 출력해주는 모듈입니다. 여기서는 24개월씩 잘라서 출력해주고 있습니다.
파이썬으로 크롤링을 하다보면 한번에 가져올 수 있는 기간이 제한되어 있는 경우가 많습니다. 아래의 코드를 돌리면 시작과 종료일자가 한쌍으로 나열된 문자열을 얻을 수 있습니다.
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
from datetime import datetime
import pandas as pd
from dateutil.relativedelta import relativedelta
from pandas import Series, DataFrame
# input / output : 'yyyymm' or 'yyyymmdd' 형태
def get_date(current, value, opt='month'):
year = int(current[:4])
month = int(current[4:6])
day = int(current[6:]) if current[6:] else 1
if opt=='month':
delta = datetime(year,month,day) + relativedelta(months=value)
new_date = str(delta.year) + str(delta.month).zfill(2)
elif opt=='day':
delta = datetime(year,month,day) + relativedelta(days=value)
new_date = ''.join(str(delta.date()).split("-"))
return new_date
def month_delta(start_month, end_month):
start_date = datetime(int(start_month[:4]), int(start_month[4:6]), 1)
end_date = datetime(int(end_month[:4]), int(end_month[4:6]), 1)
delta = relativedelta(end_date, start_date)
# >>> relativedelta(years=+2, months=+3, days=+28)
return 12 * delta.years + delta.months
start_month='199501'
end_month='202103'
total_months = month_delta(start_month, end_month)
month_num = 0
start_month_num=0
interval=24
while month_num < total_months:
month_num=month_num+interval
if end_month<get_date(start_month, month_num-1, opt='month') :
print(get_date(start_month, start_month_num, opt='month'), end_month)
break
print(get_date(start_month, start_month_num, opt='month'), get_date(start_month, month_num-1, opt='month'))
start_month_num=start_month_num+interval
|
cs |
실행결과
199501 199612
199701 199812
199901 200012
200101 200212
200301 200412
200501 200612
200701 200812
200901 201012
201101 201212
201301 201412
201501 201612
201701 201812
201901 202012
202101 202103
반응형