2021-04-22
openpyxl모듈을 이용해서 excel의 내용을 가져 오다보면, date형식으로 된 값들이 5자리의 숫자로 표시 될 때가 있다.
excel에서 날짜를 숫자로 표시하는 방식 때문이다.
해당 숫자는 1899년 12월 30일 이후부터의 날짜를 숫자로 표시하는 방식인데, 아래는 해당 방식을 함수로 구현해 놓은 것이다.
import datetime
import re

# 날짜형식을 숫자로 변경
def excel_d2n(date):
	dd = re.findall('\d+', date)
	return (datetime.datetime(int(dd[0]),int(dd[1]),int(dd[2])) - datetime.datetime(1899,12,30)).days

# 숫자 형식을 날짜로 변경
def excel_n2d(num):
	return (datetime.date(1899,12,30) + datetime.timedelta(int(num))).strftime('%Y-%m-%d')
아래는 사용 예이다
In [14]: excel_d2n('2021-12-13') Out[14]: 44543 In [15]: excel_d2n('2021/12/13') Out[15]: 44543 In [17]: excel_n2d(44197) Out[17]: '2021-01-01' In [18]: excel_n2d(44543) Out[18]: '2021-12-13'