[파이썬] time 함수 사용해서 간단한 디지털 시계 만들기
아직 넘파이와 판다스를 배우지 못해
배열을 사용해 간단한 디지털 시계를 만들었다.
첫번재, 대충 이렇게 굴러가는 시계
두번째, 아스키 아트를 이용해서 돌아가는 시계.
time 모듈 공부 내
time 함수
time() 함수는 1970년 1월 1일 0시 0분 0초 이후로 경과한 시간을 초로 반환한다.
time.time()으로 현재 시간을 구할 수 있다.
시간대는 UTC(Universal Time Coordinated, 협정 세계시)를 사용한다.
import time
print(time.time())
출력결과
localtime 함수
localtime() 함수는 time() 함수에서 반환한 값을 날짜와 시간 형태로 반환해 준다.
time.localtime(time.time())으로 현재 시간을 구할 수 있다.
특히 localtime이라는 이름 그대로 현재 지역대의 시간대를 사용한다.
우리나라에서 실행한다면 UTC에 9시간을 더한 KST(Korean Standard Time, 한국 표준시)를 사용한다.
여기서 tm_wday는 요일(월요일~일요일, 0~6), tm_yday는 1월 1일부터 경과한 일수, tmisdst=0은 서머타임 여부이다.
import time
print(time.localtime(time.time()))
출력결과
strftime 함수
strftime()함수는 localtime() 함수로 만든 객체를 포맷에 맞춰 출력한다.
"%Y는 연, %d는 일인데, %Y-%m-%d는 연-월-일 포멧이라는 뜻이다.
그리고 %c는 날짜와 시간을 함께 출력한다.
import time
print(time.localtime(time.time()))
print(time.strftime('%Y-%m-%d', time.localtime(time.time())))
print(time.strftime('%c', time.localtime(time.time())))
출력결과
참고로 strtime에서 사용하는 포멧은 다음과 같다.
- %a: 요일 축약 (Sun, Mon, Tue, ...)
- %A: 요일 (Sunday, Monday, Tuesday, ...)
- %w: 요일 (0~6, 0=Sunday)
- %d: 일 (01~31)
- %b: 월 축약 (Jan, Feb, Mar, ...)
- %B: 월 (January, February, March, ...)
- %m: 월 (01~12)
- %y: 연도 축약 (00~99)
- %Y: 연도 (ex: 2022)
- %H: 시 (00~23)
- %I: 시 (01~12)
- %p: 오전/오후 (AM, PM)
- %M: 분 (00~59)
- %S: 초 (00~59)
- %f: 마이크로초 (000000~999999)
- %z: UTC 차이 (+0900)
- %Z: 시간대 (KST)
- %j: 1월 1일부터 경과된 일수 (001~366)
- %U: 1년 중 몇 번째 주인지 (00~53, 일요일을 한 주의 시작으로 계산)
- %W: 1년 중 몇 번째 주인지 (00~53, 월요일을 한 주의 시작으로 계산)
- %c: 날짜와 시간 (Tue Aug 16 21:30:00 1988)
- %x: 날짜 (08/16/88)
- %X: 시간 (21:30:00)
- %%: % 문자 자체
datetime 모듈
today 메서드
datetime.datetime.today() 메서드는 현재 날짜와 시간을 구한다.
import datetime
print(datetime.datetime.today())
now 메서드
datetime.datetime.now(timezone) 메서드는 인자로 받은 시간대의 현재 시간을 구한다.
import datetime
import pytz
kst = pytz.timezone('Asia/Seoul')
print(datetime.datetime.now(kst))
만약 이런 오류가 뜬다면
파이참 설정 - 왼쪽에 실행하고 있는 프로젝트 - 인터프리터 - pytz 검색해서 설치해준다.
실행결과
timedelta 클래스
timedelta() 클래스는 두 날짜와 시간 사이의 차이를 계산할 때 사용한다.
timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)로 객체를 만들 수 있다.
from datetime import datetime, timedelta
d = datetime(2023, 1, 1)
td = timedelta(days=100, seconds=3600)
print(d + td)
위의 코드는 2023년 1월 1일에 100일을 더하고, 3600초를 더한 날을 계산것을 출력해 준다.
출력결과
시계만들기(배열사용)
코드
import time
import os
number = {
'0': [
["■", "■", "■", "■"],
["■", " ", " ", "■"],
["■", " ", " ", "■"],
["■", " ", " ", "■"],
["■", "■", "■", "■"]
],
'1': [
[" ", " ", " ", "■"],
[" ", " ", " ", "■"],
[" ", " ", " ", "■"],
[" ", " ", " ", "■"],
[" ", " ", " ", "■"]
],
'2': [
["■", "■", "■", "■"],
[" ", " ", " ", "■"],
["■", "■", "■", "■"],
["■", " ", " ", " "],
["■", "■", "■", "■"]
],
'3': [
["■", "■", "■", "■"],
[" ", " ", " ", "■"],
["■", "■", "■", "■"],
[" ", " ", " ", "■"],
["■", "■", "■", "■"]
],
'4': [
["■", " ", "■", " "],
["■", " ", "■", " "],
["■", "■", "■", "■"],
[" ", " ", "■", " "],
[" ", " ", "■", " "]
],
'5': [
["■", "■", "■", "■"],
["■", " ", " ", " "],
["■", "■", "■", "■"],
[" ", " ", " ", "■"],
["■", "■", "■", "■"],
],
'6': [
["■", " ", " ", " "],
["■", " ", " ", " "],
["■", "■", "■", "■"],
["■", " ", " ", "■"],
["■", "■", "■", "■"]
],
'7': [
["■", "■", "■", "■"],
["■", " ", " ", "■"],
["■", " ", " ", "■"],
[" ", " ", " ", "■"],
[" ", " ", " ", "■"],
],
'8': [
["■", "■", "■", "■"],
["■", " ", " ", "■"],
["■", "■", "■", "■"],
["■", " ", " ", "■"],
["■", "■", "■", "■"]
],
'9': [
["■", "■", "■", "■"],
["■", " ", " ", "■"],
["■", "■", "■", "■"],
[" ", " ", " ", "■"],
[" ", " ", " ", "■"]
],
':': [
[" ", "■ "],
[" ", " "],
[" ", " "],
[" ", " "],
[" ", "■ "]
]
}
while True:
now_time = time.strftime('%I %M %S', time.localtime(time.time()))
H_1 = now_time[0] # 첫번째 시간
H_2 = now_time[1] # 두번째 시간
M_1 = now_time[3] # 첫번째 분
M_2 = now_time[4] # 두번째 분
C_1 = now_time[6] # 첫번째 초
C_2 = now_time[7] # 두번째 초
for i in range(5):
for j in number[H_1][i]:
print(j, end=' ')
for j in number[H_2][i]:
print(j, end=' ')
for j in number[':'][i]:
print(j, end=' ')
for j in number[M_1][i]:
print(j, end=' ')
for j in number[M_2][i]:
print(j, end=' ')
for j in number[':'][i]:
print(j, end=' ')
for j in number[C_1][i]:
print(j, end=' ')
for j in number[C_2][i]:
print(j, end=' ')
print()
time.sleep(1)
os.system("cls")
1. 딕셔너리에 0부터 9까지의 배열을 5줄로 넣어주었다. 리스트 형식으로 넣어서 슬라이싱으로 꺼내 쓸 수 있도록 했다.
2. time 모듈을 불러온 후 strftime 함수를 사용해 시간(%I), 분(%M), 초(%S)를 출력했다.
** 1시부터 12시까지 출력은 %I를, 1부터 24시까지는 %H포메팅을 사용한다.
** %M은 분, %m은 월이다. 헷갈리지 말자!!
3. 편의를 위해서 H_1, H_2.. 이런 식으로 시간과 분과 초를 가져와서 각자의 변수에 저장해준다.
4. 배열이 총 5개이니 for문은 5번 돌아간다. 무조건 한줄씩 출력되는 형식으로 만들어야 되기 때문에(아래 사진참고)
5. 각 숫자는 딕셔너리에서 받아와서 한 줄씩 출력해준다. 옆으로 → 쌓여야 하는 형식이므로 end = ' ' 로 써준다.
6. 한 줄이 끝날때마다 개행이 되어야 하므로 for문이 끝날 때 print()를 해 주었다.
7. 시계가 깜빡거리는 것처럼 하기 위해 sleep(1)을 사용해 1초마다 출력되도록 했다.
8. 또한 import os를 하고 os.system("cls")를 그 밑에 넣어 콘솔화면이 지워지도록 만들었다.
** 만약 콘솔창이 cls 되지 않는다면 Run -> Edit Configurations -> Emulate termianl in output console을 눌러준다.
그럼 이렇게 시계처럼 출력된다.
시계만들기(아스키 아트 활용)
코드
import time
import datetime
time_art = {
'0': [' __', '| |', '|__|'],
'1': [' ', '|', '|'],
'2': [' __', ' __|', ' |__'],
'3': [' __', '__|', '__|'],
'4': [' ', '|__|', ' |'],
'5': [' __', '|__', '__|'],
'6': [' __', '|__', '|__|'],
'7': ['__', ' |', ' |'],
'8': [' __', '|__|', '|__|'],
'9': [' __', '|__|', ' __|'],
':': [' . ', ' ', ' . ']
}
clock_art_top = '''
,--.-----.--.
|--|-----|--|
|--| |--|
| |-----| |
__|--| |--|__
/ | |-----| | \\\\
/ \\__|-----|__/ \\\\
/ ______---______ \\\\
/ / \\ \\
{ / \\ }'''
clock_art_bottom = '''
| { } |
{ \\ / }
\\ `------___------' /\\
\\ __|-----|__ /\\/
\\ / |-----| \\ /
\\ |--| |--| /
--| |-----| |--
|--| |--|
|--|-----|--|
`--'-----`--'
'''
space = f"{' '* 2}"
while True:
now_time = time.strftime('%I:%M', time.localtime(time.time()))
H_1 = now_time[0] #첫번째 시간
H_2 = now_time[1] #두번째 시간
M_1 = now_time[3] #첫번째 분
M_2 = now_time[4] #두번째 분
print(clock_art_top)
for i in range(3):
if len(time_art[H_1]) == 2 and i == 2:
continue
print(space, time_art[H_1][i], end=' ')
if len(time_art[H_2]) == 2 and i == 2:
continue
print(time_art[H_2][i], end=' ')
print(time_art[':'][i], end=' ')
if len(time_art[M_1]) == 2 and i == 2:
continue
print(time_art[M_1][i], end=' ')
if len(time_art[M_2]) == 2 and i == 2:
continue
print(time_art[M_2][i], end=' ')
print()
print(clock_art_bottom)
time.sleep(1)
살짝 맘에 안드는 코드. ...
일단 자야되니까 설명은 내일 추가 예정..