본문 바로가기

개발/Python

julian date 계산

1. datetime 이용

1
2
3
import datetime
 
int(datetime.datetime(2018104).strftime("%j"))

 

2. 직접 계산

1
2
3
4
5
6
7
8
9
10
11
12
def juldate(year, month, day):
    jmonth = [0315990120151181212243273304334]
    jday = jmonth[month - 1+ day
 
    if (year % 4 == 0 and year % 100 != 0or year % 400 == 0:
        if month > 2:
            return jday + 1
 
    return jday
 
 
juldate(2018104)

 

2.1. 검증

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import datetime
 
 
def juldate(year, month, day):
    jmonth = [0315990120151181212243273304334]
    jday = jmonth[month - 1+ day
 
    if (year % 4 == 0 and year % 100 != 0or year % 400 == 0:
        if month > 2:
            return jday + 1
 
    return jday
 
 
dt = datetime.date.fromtimestamp(0)
while dt.year <= 4000:
    if int(datetime.datetime(dt.year, dt.month, dt.day).strftime("%j")) != juldate(dt.year, dt.month, dt.day):
        print(dt)
        break
 
    dt += datetime.timedelta(days=1)

 

성능 측정을 해봤다.

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
import datetime
import timeit
 
 
def juldate(year, month, day):
    jmonth = [0315990120151181212243273304334]
    jday = jmonth[month - 1+ day
 
    if (year % 4 == 0 and year % 100 != 0or year % 400 == 0:
        if month > 2:
            return jday + 1
 
    return jday
 
 
start = timeit.default_timer()
 
dt = datetime.date.fromtimestamp(0)
while dt.year <= 4000:
    juldate(dt.year, dt.month, dt.day)
    dt += datetime.timedelta(days=1)
 
end = timeit.default_timer()
print(end - start)
 
start = timeit.default_timer()
 
dt = datetime.date.fromtimestamp(0)
while dt.year <= 4000:
    int(datetime.datetime(dt.year, dt.month, dt.day).strftime("%j"))
    dt += datetime.timedelta(days=1)
 
end = timeit.default_timer()
print(end - start)
 
 
 
 
1.6149210810011292
2.9324835093567865

 

2배 정도 차이

'개발 > Python' 카테고리의 다른 글

python netCDF4 패키지 설치  (0) 2018.10.04
Python ctypes 구조체 사용  (0) 2018.10.04