기상청 Open API 이용하여 날씨 정보 가져오기
기상청 Open API 인증키 발급 신청
- 기상청 Open API를 활용하여 날씨 정보를 얻어보려고 합니다.
- Open API를 사용하기 위해서는 인증 정보가 필요하기 때문에 공공 데이터 포털 사이트에서 API 활용 신청 후 인증키를 발급 받도록 해야 합니다.
- 인증키 신청 공공 데이터 포털 사이트
- 신청 방법
더보기활용 신청 누르기
활용 목적 작성하고 하단에 원하는 정보 선택하여 신청하면 됩니다. 신청 후 마이페이지 들어가면 인증키 (Encoding, Decoding)가 보이고 API 신청으로 들어가서 신청한 API 선택하면 상세하게 확인할 수 있습니다.
- 사이트에 접속하게 되면 필요한 요청 값과 그에 대한 응답 값에 대한 정보가 나와 있고 해당 API를 이용하기 위한 언어별 예제 코드도 있습니다.
- Request, Response 정보
더보기
필요한 요청 값에 대한 정보 반환되는 응답 값에 대한 정보입니다. - 샘플 코드
- Request, Response 정보
기상청_단기예보 ((구)_동네예보) 조회서비스
초단기실황, 초단기예보, 단기((구)동네)예보, 예보버전 정보를 조회하는 서비스입니다. 초단기실황정보는 예보 구역에 대한 대표 AWS 관측값을, 초단기예보는 예보시점부터 6시간까지의 예보를,
www.data.go.kr
기본적인 사용 방법
1. XML 형식
from datetime import datetime, timedelta
import json
import requests
'''
참고사항
날씨 조회는 오늘 기준으로 3일 이내의 자료만 조회할 수 있습니다. 3일이 넘어가면 3일 이내의 자료만 조회할 수 있다는 응답을 해줍니다.
serviceKey에는 Decoding Key가 아니면 에러가 발생하는 것을 확인했습니다. DecodingKey를 넣어주세요
날짜와 시간은 특수문자 없이 시간을 이어서 써주시면 됩니다.
EX) base_date = '20240905', base_time = '1000' <- 2024년 9월 5일 10시 날씨 정보를 원한다라는 의미입니다.
nx와 ny는 API 신청 링크 들어가면 참고문서로 엑셀 파일이 있습니다. 엑셀 파일을 열어보면 확인할 수 있습니다.
원하는 지역의 nx 값과 ny 값을 찾아 입력해주면 됩니다.
요청주소 http://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getUltraSrtFcst
'''
url = 'http://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getUltraSrtFcst'
params ={'serviceKey' : '이곳에 발급 받은 인증키 입력해주면 됩니다.', 'pageNo' : '페이지 번호', 'numOfRows' : '한 페이지 결과 수', 'dataType' : '응답 자료 형식', 'base_date' : '발표일자', 'base_time' : '발표시간', 'nx' : '예보지점 X 좌표', 'ny' : '예보지점 Y 좌표' }
response = requests.get(url, params=params)
print(response.content)
더보기
b'<?xml version="1.0" encoding="UTF-8"?>\r\n<response><header><resultCode>00<resultCode><resultMsg>NORMAL_SERVICE<resultMsg><header><body><dataType>XML<dataType><items>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>LGT</category><fcstDate>20240905</fcstDate><fcstTime>1100</fcstTime><fcstValue>0</fcstValue><nx>59</nx><ny>125</ny><item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>LGT</category><fcstDate>20240905</fcstDate><fcstTime>1200</fcstTime><fcstValue>0</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>LGT</category><fcstDate>20240905</fcstDate><fcstTime>1300</fcstTime><fcstValue>0</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>LGT</category><fcstDate>20240905</fcstDate><fcstTime>1400</fcstTime><fcstValue>0</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>LGT</category><fcstDate>20240905</fcstDate><fcstTime>1500</fcstTime><fcstValue>0</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>LGT</category><fcstDate>20240905</fcstDate><fcstTime>1600</fcstTime><fcstValue>0</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>PTY</category><fcstDate>20240905</fcstDate><fcstTime>1100</fcstTime><fcstValue>0</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>PTY</category><fcstDate>20240905</fcstDate><fcstTime>1200</fcstTime><fcstValue>0</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>PTY</category><fcstDate>20240905</fcstDate><fcstTime>1300</fcstTime><fcstValue>1</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>PTY</category><fcstDate>20240905</fcstDate><fcstTime>1400</fcstTime><fcstValue>1</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>PTY</category><fcstDate>20240905</fcstDate><fcstTime>1500</fcstTime><fcstValue>1</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>PTY</category><fcstDate>20240905</fcstDate><fcstTime>1600</fcstTime><fcstValue>0</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>RN1</category><fcstDate>20240905</fcstDate><fcstTime>1100</fcstTime><fcstValue>\xea\xb0\x95\xec\x88\x98\xec\x97\x86\xec\x9d\x8c</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>RN1</category><fcstDate>20240905</fcstDate><fcstTime>1200</fcstTime><fcstValue>\xea\xb0\x95\xec\x88\x98\xec\x97\x86\xec\x9d\x8c</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>RN1</category><fcstDate>20240905</fcstDate><fcstTime>1300</fcstTime><fcstValue>3.0mm</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>RN1</category><fcstDate>20240905</fcstDate><fcstTime>1400</fcstTime><fcstValue>2.0mm</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>RN1</category><fcstDate>20240905</fcstDate><fcstTime>1500</fcstTime><fcstValue>1mm \xeb\xaf\xb8\xeb\xa7\x8c</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>RN1</category><fcstDate>20240905</fcstDate><fcstTime>1600</fcstTime><fcstValue>\xea\xb0\x95\xec\x88\x98\xec\x97\x86\xec\x9d\x8c</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>SKY</category><fcstDate>20240905</fcstDate><fcstTime>1100</fcstTime><fcstValue>4</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>SKY</category><fcstDate>20240905</fcstDate><fcstTime>1200</fcstTime><fcstValue>4</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>SKY</category><fcstDate>20240905</fcstDate><fcstTime>1300</fcstTime><fcstValue>4</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>SKY</category><fcstDate>20240905</fcstDate><fcstTime>1400</fcstTime><fcstValue>4</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>SKY</category><fcstDate>20240905</fcstDate><fcstTime>1500</fcstTime><fcstValue>4</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>SKY</category><fcstDate>20240905</fcstDate><fcstTime>1600</fcstTime><fcstValue>4</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>T1H</category><fcstDate>20240905</fcstDate><fcstTime>1100</fcstTime><fcstValue>29</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>T1H</category><fcstDate>20240905</fcstDate><fcstTime>1200</fcstTime><fcstValue>29</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>T1H</category><fcstDate>20240905</fcstDate><fcstTime>1300</fcstTime><fcstValue>29</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>T1H</category><fcstDate>20240905</fcstDate><fcstTime>1400</fcstTime><fcstValue>28</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>T1H</category><fcstDate>20240905</fcstDate><fcstTime>1500</fcstTime><fcstValue>28</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>T1H</category><fcstDate>20240905</fcstDate><fcstTime>1600</fcstTime><fcstValue>28</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>REH</category><fcstDate>20240905</fcstDate><fcstTime>1100</fcstTime><fcstValue>60</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>REH</category><fcstDate>20240905</fcstDate><fcstTime>1200</fcstTime><fcstValue>65</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>REH</category><fcstDate>20240905</fcstDate><fcstTime>1300</fcstTime><fcstValue>70</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>REH</category><fcstDate>20240905</fcstDate><fcstTime>1400</fcstTime><fcstValue>75</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>REH</category><fcstDate>20240905</fcstDate><fcstTime>1500</fcstTime><fcstValue>80</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>REH</category><fcstDate>20240905</fcstDate><fcstTime>1600</fcstTime><fcstValue>80</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>UUU</category><fcstDate>20240905</fcstDate><fcstTime>1100</fcstTime><fcstValue>1</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>UUU</category><fcstDate>20240905</fcstDate><fcstTime>1200</fcstTime><fcstValue>1.8</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>UUU</category><fcstDate>20240905</fcstDate><fcstTime>1300</fcstTime><fcstValue>1.5</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>UUU</category><fcstDate>20240905</fcstDate><fcstTime>1400</fcstTime><fcstValue>1.8</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>UUU</category><fcstDate>20240905</fcstDate><fcstTime>1500</fcstTime><fcstValue>1.7</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>UUU</category><fcstDate>20240905</fcstDate><fcstTime>1600</fcstTime><fcstValue>1.7</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>VVV</category><fcstDate>20240905</fcstDate><fcstTime>1100</fcstTime><fcstValue>2.4</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>VVV</category><fcstDate>20240905</fcstDate><fcstTime>1200</fcstTime><fcstValue>1.9</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>VVV</category><fcstDate>20240905</fcstDate><fcstTime>1300</fcstTime><fcstValue>1.5</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>VVV</category><fcstDate>20240905</fcstDate><fcstTime>1400</fcstTime><fcstValue>1.1</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>VVV</category><fcstDate>20240905</fcstDate><fcstTime>1500</fcstTime><fcstValue>1.2</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>VVV</category><fcstDate>20240905</fcstDate><fcstTime>1600</fcstTime><fcstValue>1.1</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>VEC</category><fcstDate>20240905</fcstDate><fcstTime>1100</fcstTime><fcstValue>203</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>VEC</category><fcstDate>20240905</fcstDate><fcstTime>1200</fcstTime><fcstValue>223</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>VEC</category><fcstDate>20240905</fcstDate><fcstTime>1300</fcstTime><fcstValue>226</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>VEC</category><fcstDate>20240905</fcstDate><fcstTime>1400</fcstTime><fcstValue>238</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>VEC</category><fcstDate>20240905</fcstDate><fcstTime>1500</fcstTime><fcstValue>235</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>VEC</category><fcstDate>20240905</fcstDate><fcstTime>1600</fcstTime><fcstValue>237</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>WSD</category><fcstDate>20240905</fcstDate><fcstTime>1100</fcstTime><fcstValue>3</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>WSD</category><fcstDate>20240905</fcstDate><fcstTime>1200</fcstTime><fcstValue>3</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>WSD</category><fcstDate>20240905</fcstDate><fcstTime>1300</fcstTime><fcstValue>2</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>WSD</category><fcstDate>20240905</fcstDate><fcstTime>1400</fcstTime><fcstValue>2</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>WSD</category><fcstDate>20240905</fcstDate><fcstTime>1500</fcstTime><fcstValue>2</fcstValue><nx>59</nx><ny>125</ny></item>
<item><baseDate>20240905</baseDate><baseTime>1030</baseTime><category>WSD</category><fcstDate>20240905</fcstDate><fcstTime>1600</fcstTime><fcstValue>2</fcstValue><nx>59</nx><ny>125</ny></item></items>
<numOfRows>60</numOfRows><pageNo>1</pageNo><totalCount>60</totalCount></body></response>\r\n'
2. JSON 형식
from datetime import datetime, timedelta
import json
import requests
'''
참고사항
날씨 조회는 오늘 기준으로 3일 이내의 자료만 조회할 수 있습니다. 3일이 넘어가면 3일 이내의 자료만 조회할 수 있다는 응답을 해줍니다.
serviceKey에는 EncodingKey 값을 넣어주면 됩니다.
날짜와 시간은 특수문자 없이 시간을 이어서 써주시면 됩니다.
EX) base_date = '20240905', base_time = '1000' <- 2024년 9월 5일 10시 날씨 정보를 원한다라는 의미입니다.
nx와 ny는 API 신청 링크 들어가면 참고문서로 엑셀 파일이 있습니다. 엑셀 파일을 열어보면 확인할 수 있습니다.
원하는 지역의 nx 값과 ny 값을 찾아 입력해주면 됩니다.
http://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getUltraSrtFcst
'''
serviceKey = "이곳에 발급 받은 인증키 입력해주면 됩니다."
numOfRows = 한 페이지 결과 수
pageNO = 페이지 번호
dataType = '응답 자료 형식'
base_date = '발표일자'
base_time = '발표시각'
nx = 예보지점 X 좌표
ny = 예보지점 Y 좌표
url = f"http://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getUltraSrtFcst?serviceKey={serviceKey}&numOfRows={numOfRows}&pageNo={pageNO}&dataType={dataType}&base_date={base_date}&base_time={base_time}&nx={nx}&ny={ny}"
response = requests.get(url)
res = json.loads(response.text)
print(res)
더보기
{'response': {'header': {'resultCode': '00', 'resultMsg': 'NORMAL_SERVICE'
}, 'body': {'dataType': 'JSON', 'items': {'item': [
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'LGT', 'fcstDate': '20240905', 'fcstTime': '1100', 'fcstValue': '0', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'LGT', 'fcstDate': '20240905', 'fcstTime': '1200', 'fcstValue': '0', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'LGT', 'fcstDate': '20240905', 'fcstTime': '1300', 'fcstValue': '0', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'LGT', 'fcstDate': '20240905', 'fcstTime': '1400', 'fcstValue': '0', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'LGT', 'fcstDate': '20240905', 'fcstTime': '1500', 'fcstValue': '0', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'LGT', 'fcstDate': '20240905', 'fcstTime': '1600', 'fcstValue': '0', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'PTY', 'fcstDate': '20240905', 'fcstTime': '1100', 'fcstValue': '0', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'PTY', 'fcstDate': '20240905', 'fcstTime': '1200', 'fcstValue': '0', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'PTY', 'fcstDate': '20240905', 'fcstTime': '1300', 'fcstValue': '1', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'PTY', 'fcstDate': '20240905', 'fcstTime': '1400', 'fcstValue': '1', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'PTY', 'fcstDate': '20240905', 'fcstTime': '1500', 'fcstValue': '1', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'PTY', 'fcstDate': '20240905', 'fcstTime': '1600', 'fcstValue': '0', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'RN1', 'fcstDate': '20240905', 'fcstTime': '1100', 'fcstValue': '강수없음', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'RN1', 'fcstDate': '20240905', 'fcstTime': '1200', 'fcstValue': '강수없음', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'RN1', 'fcstDate': '20240905', 'fcstTime': '1300', 'fcstValue': '3.0mm', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'RN1', 'fcstDate': '20240905', 'fcstTime': '1400', 'fcstValue': '2.0mm', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'RN1', 'fcstDate': '20240905', 'fcstTime': '1500', 'fcstValue': '1mm 미만', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'RN1', 'fcstDate': '20240905', 'fcstTime': '1600', 'fcstValue': '강수없음', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'SKY', 'fcstDate': '20240905', 'fcstTime': '1100', 'fcstValue': '4', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'SKY', 'fcstDate': '20240905', 'fcstTime': '1200', 'fcstValue': '4', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'SKY', 'fcstDate': '20240905', 'fcstTime': '1300', 'fcstValue': '4', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'SKY', 'fcstDate': '20240905', 'fcstTime': '1400', 'fcstValue': '4', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'SKY', 'fcstDate': '20240905', 'fcstTime': '1500', 'fcstValue': '4', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'SKY', 'fcstDate': '20240905', 'fcstTime': '1600', 'fcstValue': '4', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'T1H', 'fcstDate': '20240905', 'fcstTime': '1100', 'fcstValue': '29', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'T1H', 'fcstDate': '20240905', 'fcstTime': '1200', 'fcstValue': '28', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'T1H', 'fcstDate': '20240905', 'fcstTime': '1300', 'fcstValue': '28', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'T1H', 'fcstDate': '20240905', 'fcstTime': '1400', 'fcstValue': '28', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'T1H', 'fcstDate': '20240905', 'fcstTime': '1500', 'fcstValue': '28', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'T1H', 'fcstDate': '20240905', 'fcstTime': '1600', 'fcstValue': '28', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'REH', 'fcstDate': '20240905', 'fcstTime': '1100', 'fcstValue': '60', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'REH', 'fcstDate': '20240905', 'fcstTime': '1200', 'fcstValue': '65', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'REH', 'fcstDate': '20240905', 'fcstTime': '1300', 'fcstValue': '65', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'REH', 'fcstDate': '20240905', 'fcstTime': '1400', 'fcstValue': '75', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'REH', 'fcstDate': '20240905', 'fcstTime': '1500', 'fcstValue': '75', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'REH', 'fcstDate': '20240905', 'fcstTime': '1600', 'fcstValue': '80', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'UUU', 'fcstDate': '20240905', 'fcstTime': '1100', 'fcstValue': '2.6', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'UUU', 'fcstDate': '20240905', 'fcstTime': '1200', 'fcstValue': '3.2', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'UUU', 'fcstDate': '20240905', 'fcstTime': '1300', 'fcstValue': '2.5', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'UUU', 'fcstDate': '20240905', 'fcstTime': '1400', 'fcstValue': '2.2', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'UUU', 'fcstDate': '20240905', 'fcstTime': '1500', 'fcstValue': '1.8', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'UUU', 'fcstDate': '20240905', 'fcstTime': '1600', 'fcstValue': '1.7', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'VVV', 'fcstDate': '20240905', 'fcstTime': '1100', 'fcstValue': '2.5', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'VVV', 'fcstDate': '20240905', 'fcstTime': '1200', 'fcstValue': '2', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'VVV', 'fcstDate': '20240905', 'fcstTime': '1300', 'fcstValue': '1.5', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'VVV', 'fcstDate': '20240905', 'fcstTime': '1400', 'fcstValue': '1.2', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'VVV', 'fcstDate': '20240905', 'fcstTime': '1500', 'fcstValue': '1.2', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'VVV', 'fcstDate': '20240905', 'fcstTime': '1600', 'fcstValue': '1.1', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'VEC', 'fcstDate': '20240905', 'fcstTime': '1100', 'fcstValue': '226', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'VEC', 'fcstDate': '20240905', 'fcstTime': '1200', 'fcstValue': '238', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'VEC', 'fcstDate': '20240905', 'fcstTime': '1300', 'fcstValue': '239', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'VEC', 'fcstDate': '20240905', 'fcstTime': '1400', 'fcstValue': '242', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'VEC', 'fcstDate': '20240905', 'fcstTime': '1500', 'fcstValue': '236', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'VEC', 'fcstDate': '20240905', 'fcstTime': '1600', 'fcstValue': '237', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'WSD', 'fcstDate': '20240905', 'fcstTime': '1100', 'fcstValue': '4', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'WSD', 'fcstDate': '20240905', 'fcstTime': '1200', 'fcstValue': '4', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'WSD', 'fcstDate': '20240905', 'fcstTime': '1300', 'fcstValue': '3', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'WSD', 'fcstDate': '20240905', 'fcstTime': '1400', 'fcstValue': '3', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'WSD', 'fcstDate': '20240905', 'fcstTime': '1500', 'fcstValue': '2', 'nx': 59, 'ny': 125
},
{'baseDate': '20240905', 'baseTime': '1030', 'category': 'WSD', 'fcstDate': '20240905', 'fcstTime': '1600', 'fcstValue': '2', 'nx': 59, 'ny': 125
}
]
}, 'pageNo': 1, 'numOfRows': 60, 'totalCount': 60
}
}
}
- category 정리
더보기
항목값 항목명 단위 bit T1H 기온 °C 10 RN1 1시간 강수량 범주 (1mm) 8 SKY 하늘상태 코드값 4 UUU 동서바람성분 m/s 12 VVV 남북바람성분 m/s 12 REH 습도 % 8 PTY 강수형태 코드값 4 LGT 낙뢰 kA(킬로암페어) 4 VEC 풍향 deg 10 WSD 풍속 m/s 10 하늘상태(SKY)코드 맑음(1), 구름많음(3), 흐림(4) 강수형태(PTY)코드 (초단기) 없음(0), 비(1), 비/눈(2), 눈(3), 빗방울(5), 빗방울눈날림(6), 눈날림(7) - 위 두 개의 코드는 사실 똑같은 코드나 다름 없습니다 다만 다양한 방법으로 접근하는 방법을 설명드리고 싶어 두 개 다 가져와 봤습니다.
- 첫 번째 코드에도 dataType을 json으로 바꿔주면 json 형태로 조회가 되고 두 번째 코드 또한 xml로 바꿔주면 xml 형태로 조회가 됩니다.
- 참고사항에 나와 있듯이 첫 번째는 serviceKey를 decodingKey로 넣어줘야 하고 두 번째 코드는 encodingKey 값을 넣어주어야 합니다.
원하는 형태로 정보 가져오기
1. Custom
- 받아온 날씨 정보를 사용자가 알아보기 편하도록 수정하려고 합니다.
- 수정하려는 형태는
X년 X월 X일 X시 X분 (방위정보) 지역의 날씨는 하늘상태 | 강수형태 | 1시간 강수량 | 기온 | 습도 | 동서바람 | 남북바람 | 풍향 | 풍속 | 낙뢰 - 이렇게 바꿔보도록 하겠습니다.
2. 시간별 정도
- 시간별로 category 정보를 모아 한 줄로 표현할 수 있게 합니다.
# 받아온 날씨 정보를 원하는 형식으로 수정 # category를 한 줄로 취합하여 시간대 별로 분류 informations = dict() for items in res['response']['body']['items']['item']: cate = items['category'] fcstTime = items['fcstTime'] fcstValue = items['fcstValue'] temp = dict() temp[cate] = fcstValue if fcstTime not in informations.keys(): informations[fcstTime] = dict() informations[fcstTime][cate] = fcstValue print(informations)
3. 방위 정보
- 풍향 정보를 위해 사용할 방위 정보입니다.
# 시간대 별로 분류한 것들에 대한 방위 정보 담기 deg_code = {0 : 'N', 360 : 'N', 180 : 'S', 270 : 'W', 90 : 'E', 22.5 :'NNE', 45 : 'NE', 67.5 : 'ENE', 112.5 : 'ESE', 135 : 'SE', 157.5 : 'SSE', 202.5 : 'SSW', 225 : 'SW', 247.5 : 'WSW', 292.5 : 'WNW', 315 : 'NW', 337.5 : 'NNW'} def deg_to_dir(deg): close_dir = '' min_abs = 360 if deg not in deg_code.keys(): for key in deg_code.keys(): if abs(key - deg) < min_abs: min_abs = abs(key - deg) close_dir = deg_code[key] else: close_dir = deg_code[deg] return close_dir
4. 최종 Custom
- category의 명칭을 위 표를 활용하여 수정되어 출력될 수 있게 했습니다.
# category 값 커스텀 pty_code = {0 : '강수 없음', 1 : '비', 2 : '비/눈', 3 : '눈', 5 : '빗방울눈날림', 6 : '진눈깨비', 7 : '눈날림'} sky_code = {1 : '맑음', 3 : '구름많음', 4 : '흐림'} for key, val in zip(informations.keys(), informations.values()): template = f"""{base_date[:4]}년 {base_date[4:6]}월 {base_date[-2:]}일 {key[:2]}시 {key[2:]}분 {(int(nx), int(ny))} 지역의 날씨는 """ # 하늘 상태 - 맑음(1), 구름많음(3), 흐림(4) if val['SKY']: sky_temp = sky_code[int(val['SKY'])] template += sky_temp + " | " # 강수 형태 - (초단기) 없음(0), 비(1), 비/눈(2), 눈(3), 빗방울눈날림(5), 진눈깨비(6), 눈날림(7) if val['PTY']: pty_temp = pty_code[int(val['PTY'])] template += pty_temp + " | " # 1시간 강수량 (mm) if val['RN1']: rn1_temp = val['RN1'] template += f"시간당 {rn1_temp} | " # 기온 (°C) if val['T1H']: t1h_temp = float(val['T1H']) template += f"기온 {t1h_temp}°C | " # 습도 (%) if val['REH']: reh_temp = float(val['REH']) template += f"습도 {reh_temp}% | " # 동서 바람 성분 (m/s) if val['UUU']: uuu_temp = float(val['UUU']) template += f"동서 바람 성분 {uuu_temp}m/s | " # 남북 바람 성분 (m/s) if val['VVV']: vvv_temp = float(val['VVV']) template += f"동서 바람 성분 {vvv_temp}m/s | " # 풍향 (deg) if val['VEC']: vec_temp = deg_to_dir(float(val['VEC'])) template += f"풍향 {vec_temp} | " # 풍속 (m/s) if val['WSD']: wsd_temp = val['WSD'] template += f"풍속 {wsd_temp}m/s | " # 낙뢰 (kA) if val['LGT']: lgt_temp = val['LGT'] template += f"낙뢰 {lgt_temp}kA"
5. 출력
전체 코드
더보기
from datetime import datetime, timedelta
import json
import requests
# 설정 시간의 날씨 정보 모두 받아오기
rink = "http://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getUltraSrtFcst"
serviceKey = "이곳에 발급 받은 인증키 입력해주면 됩니다."
numOfRows = 한 페이지 결과 수
pageNO = 페이지 번호
dataType = '응답 자료 형식'
base_date = '발표일자'
base_time = '발표시각'
nx = 예보지점 X 좌표
ny = 예보지점 Y 좌표
url = f"{rink}?serviceKey={serviceKey}&numOfRows={numOfRows}&pageNo={pageNO}&dataType={dataType}&base_date={base_date}&base_time={base_time}&nx={nx}&ny={ny}"
response = requests.get(url)
res = json.loads(response.text)
# 받아온 날씨 정보를 원하는 형식으로 수정
# category를 한 줄로 취합하여 시간대 별로 분류
informations = dict()
for items in res['response']['body']['items']['item']:
cate = items['category']
fcstTime = items['fcstTime']
fcstValue = items['fcstValue']
temp = dict()
temp[cate] = fcstValue
if fcstTime not in informations.keys():
informations[fcstTime] = dict()
informations[fcstTime][cate] = fcstValue
# 시간대 별로 분류한 것들에 대한 방위 정보 담기
deg_code = {0 : 'N', 360 : 'N', 180 : 'S', 270 : 'W', 90 : 'E', 22.5 :'NNE',
45 : 'NE', 67.5 : 'ENE', 112.5 : 'ESE', 135 : 'SE', 157.5 : 'SSE',
202.5 : 'SSW', 225 : 'SW', 247.5 : 'WSW', 292.5 : 'WNW', 315 : 'NW',
337.5 : 'NNW'}
def deg_to_dir(deg):
close_dir = ''
min_abs = 360
if deg not in deg_code.keys():
for key in deg_code.keys():
if abs(key - deg) < min_abs:
min_abs = abs(key - deg)
close_dir = deg_code[key]
else:
close_dir = deg_code[deg]
return close_dir
# category 값 커스텀
pty_code = {0 : '강수 없음', 1 : '비', 2 : '비/눈', 3 : '눈', 5 : '빗방울눈날림', 6 : '진눈깨비', 7 : '눈날림'}
sky_code = {1 : '맑음', 3 : '구름많음', 4 : '흐림'}
for key, val in zip(informations.keys(), informations.values()):
template = f"""{base_date[:4]}년 {base_date[4:6]}월 {base_date[-2:]}일 {key[:2]}시 {key[2:]}분 {(int(nx), int(ny))} 지역의 날씨는 """
# 하늘 상태 - 맑음(1), 구름많음(3), 흐림(4)
if val['SKY']:
sky_temp = sky_code[int(val['SKY'])]
template += sky_temp + " | "
# 강수 형태 - (초단기) 없음(0), 비(1), 비/눈(2), 눈(3), 빗방울눈날림(5), 진눈깨비(6), 눈날림(7)
if val['PTY']:
pty_temp = pty_code[int(val['PTY'])]
template += pty_temp + " | "
# 1시간 강수량 (mm)
if val['RN1']:
rn1_temp = val['RN1']
template += f"시간당 {rn1_temp} | "
# 기온 (°C)
if val['T1H']:
t1h_temp = float(val['T1H'])
template += f"기온 {t1h_temp}°C | "
# 습도 (%)
if val['REH']:
reh_temp = float(val['REH'])
template += f"습도 {reh_temp}% | "
# 동서 바람 성분 (m/s)
if val['UUU']:
uuu_temp = float(val['UUU'])
template += f"동서 바람 성분 {uuu_temp}m/s | "
# 남북 바람 성분 (m/s)
if val['VVV']:
vvv_temp = float(val['VVV'])
template += f"동서 바람 성분 {vvv_temp}m/s | "
# 풍향 (deg)
if val['VEC']:
vec_temp = deg_to_dir(float(val['VEC']))
template += f"풍향 {vec_temp} | "
# 풍속 (m/s)
if val['WSD']:
wsd_temp = val['WSD']
template += f"풍속 {wsd_temp}m/s | "
# 낙뢰 (kA)
if val['LGT']:
lgt_temp = val['LGT']
template += f"낙뢰 {lgt_temp}kA"
print(template)
'Python' 카테고리의 다른 글
[Python] - 파이썬 형태소 분석기 (2) | 2024.09.21 |
---|---|
[Python] - 파이참 인터프리터(Interpreter) 설정 (1) | 2024.09.20 |
[Python] - 파이썬을 이용한 더미데이터 DB 저장 (0) | 2024.09.10 |
[Python] - 파이참 라이브러리 설치 (1) | 2024.09.09 |
[Python] - 파이썬 주석 (한줄, 여러줄, 단축키) (0) | 2024.09.02 |