datetime 날짜와 시간

datatime

datetime 모듈은 특정 시간과 날짜를 불러오는 파이썬 내장 모듈이다.

날짜와 시간 함수

datatime 모듈을 사용하면 시간 날짜 UTC timezone을 불러올 수 있고, 내장 함수로 data, time 등을 사용해 날짜 혹은 시간만 지정하고 특정 시간대를 지정해 불러올 수도 있다.

1
2
3
4
5
import datetime

print(datetime.date.today())
print(datetime.datetime.today())
print(datetime.time(12,59,33, microsecond=333333, tzinfo=datetime.timezone.utc))

2022-02-03
2022-02-03 03:36:07.407621
12:59:33.333333+00:00

strftime(원하는 형식으로 변경)

strftime을 사용하면 불러온 시간을 원하는 형식으로 바꿀 수 있다.

1
print(datetime.datetime.today().strftime("%Y/%m/%d %H:%M:%S"))

2022/02/03 03:40:36

외부링크

time 모듈로 일시정지

python 내장 함수인 time 모듈을 사용하면 시간 관련 추출이나 간섭을 할 수 있다.

그 중 이번에 내가 사용할 함수는 sleep() 함수로 지정한 시간 단위만큼 프로그램 실행 중간에 딜레이를 줄 수 있다.

특히 이번에 크롤링 중인 페이지가 동적페이지에 하나의 URL에서 클릭으로 HTML 코드만 바뀌는 옵션이 들어가 selenium만으로 크롤링하면 때때로 에러가 발생했다.

1
2
3
import time

time.sleep(3)

을 사용하면 코드 중간에 3초간 딜레이 줄 수 있다.

외부링크

Matplotlib의 pyplot과 pyplot.subplots

Matplotlibmatlab 수치해석 프로그램을 python 기반 작업공간에서 다양한 작업을 하기 위해 개발된 외부 라이브러리다.
이 라이브러리에서 그래프를 그리는 방식은 크게 2종류가 있는데, 간편하게 사용할 수 있는 pyplot가 첫번째다. 두번째 방식은 객체지향형 모듈에 좀 복잡한 객체 생성을 거쳐야하지만 다양한 설정 및 한 그래프 공간에 여러 축을 표현할 수 있는 pyplot.subplots가 있다.

Matplotlib 튜토리얼

pyplot API

pyplot 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import pandas as pd       ## pandas 라이브러리

f1 = "E:\\Fear\\Univ\\4-2\\대기정보전산학\\실습\\co2.csv"
f2 = "E:\\Fear\\Univ\\4-2\\대기정보전산학\\실습\\1880-2019.csv"

data1 = pd.read_csv(f1, engine='python')

styr = 1900
edyr = 2014+1 # [이상:미만] 이므로 2014 -> 2015

year = data1['year'] ### ['year'] -> year 열만 읽어낸다.
conc = data1['data_mean_global']

time = year[styr:edyr]
co2 = conc[styr:edyr]

print(co2)
## [n번째 줄] [co2값]

print(co2.head(3)) ## 위에서 n개
print(co2.tail(3)) ## 아래서 n개
1900    295.674998
1901    296.006998
1902    296.324997
1903    296.653997
1904    296.953996
           ...    
2010    388.717029
2011    390.944015
2012    393.015993
2013    395.724979
2014    397.546977
Name: data_mean_global, Length: 115, dtype: float64
1900    295.674998
1901    296.006998
1902    296.324997
Name: data_mean_global, dtype: float64
2012    393.015993
2013    395.724979
2014    397.546977
Name: data_mean_global, dtype: float64
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import numpy as np        ## numpy 라이브러리

data2 = np.genfromtxt(f2, encoding='utf8',dtype=None,delimiter=',',names=('year','value'), skip_header=5)
## 변수 / 인코딩 / 혼합 데이터 : dtype=None / 값 사이 구분 / 열 이름 지정 / 머릿말 생략 열 수

size=len(data2)

print(size)

for i in range(0,size):
t = data2['year'][i] ## year 열의 i번째 값을 t에 저장
if t == 1900:
styr = i
elif t == 2015:
edyr = i
i=i+1

print(styr)
print(edyr)

temp = data2['value'][styr:edyr]

print(temp)
140
20
135
[-0.07 -0.15 -0.25 -0.37 -0.46 -0.28 -0.21 -0.38 -0.43 -0.44 -0.4  -0.44
 -0.34 -0.32 -0.14 -0.09 -0.32 -0.39 -0.3  -0.25 -0.23 -0.16 -0.24 -0.25
 -0.24 -0.18 -0.07 -0.17 -0.18 -0.32 -0.11 -0.06 -0.13 -0.26 -0.11 -0.16
 -0.12 -0.01 -0.02  0.01  0.16  0.27  0.11  0.1   0.28  0.18 -0.01 -0.04
 -0.05 -0.07 -0.15  0.    0.04  0.13 -0.1  -0.13 -0.18  0.07  0.12  0.08
  0.05  0.09  0.1   0.12 -0.14 -0.07 -0.01  0.   -0.03  0.1   0.06 -0.07
  0.03  0.19 -0.06  0.01 -0.07  0.21  0.12  0.23  0.28  0.32  0.19  0.36
  0.17  0.16  0.24  0.38  0.39  0.29  0.45  0.39  0.24  0.28  0.34  0.47
  0.32  0.51  0.65  0.44  0.43  0.57  0.62  0.64  0.58  0.67  0.64  0.62
  0.54  0.65  0.73  0.58  0.64  0.67  0.74]

설정값이 적은 pyplot에선 아래와 같이 기본형태가 정해진 matplotlib를 로드해서 사용한다.

1
2
%matplotlib notebook  
## matplotlib 그림툴 로드
1
2
3
4
5
6
import matplotlib.pyplot as plt

plt.plot(time,co2,'b') ## 'matplotlib named color' 참고
plt.xlabel('Year')
plt.ylabel('CO₂concentration') ## 한글 유니코드, 특수문자 모두 사용가능
plt.show()
<IPython.core.display.Javascript object>

1
plt.close()
1
2
3
4
plt.plot(time,temp,'r')
plt.xlabel('Year')
plt.ylabel('Global Mean Surface Temperature')
plt.show()
<IPython.core.display.Javascript object>

1
plt.close()

pylot.subplots (객체지향 API)

pylot.subplots 예제1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
fig, ax1 = plt.subplots()   ## matplotlib.pyplot.subplots 참고
ax2 = ax1.twinx() ## 축을 하나 더 추가하기 위한 함수 twinx

ax1.set_ylabel('GMST anomaly (C)') ##
ax1.set_xlabel('Year') ## 라벨 지정
ax2.set_ylabel('CO₂(ppm)') ##

line1 = ax1.plot(time, temp, color='crimson', label='Global temperature anomaly',linewidth = 1.5)
line2 = ax2.plot(time, co2, color='limegreen', label='CO₂concentration',linewidth = 2.)

lines = line1 + line2 ## 두 장의 line 그림을 합친 변수
labels = [l.get_label() for l in lines]
ax1.legend(lines, labels, loc='upper left') ## loc 'location' ## matplotlin.axes.Axes.legend 참고


plt.show
<IPython.core.display.Javascript object>

<function matplotlib.pyplot.show(block=None)>
1
plt.close()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
fig, ax1 = plt.subplots() 
ax2 = ax1.twinx()

ax1.set_ylabel('GMST anomaly (C)')
ax1.set_xlabel('Year')
ax2.set_ylabel('CO₂(ppm)')
ax1.set_ylim([-0.46,0.72]) ## 범위 조정
ax2.set_ylim([280,390]) ##
ax1.set_xlim([1900,2014])

line1 = ax1.plot(time, temp, color='crimson', label='Global temperature anomaly',linewidth = 1.5)
line2 = ax2.plot(time, co2, color='limegreen', label='CO₂concentration',linewidth = 2.)

lines = line1 + line2
labels = [l.get_label() for l in lines]
ax1.legend(lines, labels, loc='upper left')


plt.show
<IPython.core.display.Javascript object>

<function matplotlib.pyplot.show(block=None)>
1
plt.close()

파이썬 라이브러리 math와 numpy

파이썬 모듈 기초

내장 라이브러리 Math

파이썬에는 기본적으로 수학 관련 작업을 위해 자주 사용되는 Math 내장 라이브러리가 존재한다.

1
2
3
4
import math    # math 라이브러리를 불러오는 명령어.
''' 라이브러리 명령어는 [라이브러리명(혹은 as로 지정한 임의의 명칭)].[명령어]로 사용할 수 있으며.
명령어 자동완성(혹은 명령어 목록)은 tap 키로 사용 및 확인 가능하다.
'''

math 라이브러리는 수학 연산을 도와주는 라이브러리로 삼각함수부터 1~N까지 값을 곱해주는 factorial 함수 등 다양한 작업이 가능한 기본 함수들을 제공한다.

1
2
print(math.cos( (300 / 180) * math.pi ))
print(math.factorial(4))
0.5000000000000001
24

파이썬에서 기본적으로 제공하는 List 형식의 행은 사용할 수 있으나 Math 라이브러리가 추가해주는 method 및 상수는 기본적인 식과 pi 등의 상수 뿐으로 다차원 연산으로 인해 행렬이 필요한 vector나 선형대수 등의 작업 형식에 대해선 복잡해지는 불편함이 있다.

외부 라이브러리 Numpy

위 문제를 해결해주는 라이브러리가 C언어 기반으로 만들어진 Numpy 외부 라이브러리로 작업 공간에서 행렬 형식의 변수를 사용할 수 있게 도와준다.

numpy 명령어 튜토리얼

1
2
import numpy as np
print(np.__version__)
1.20.1