“매일 아침 6시에 텔레그램 메시지를 보내고 싶은데, 어떻게 해야 할까요?”
Python을 처음 배우는 분들이 가장 많이 궁금해하는 질문 중 하나입니다. 시간 기반 자동화는 생각보다 간단하게 구현할 수 있습니다. 이 글에서는 Python의 datetime 모듈과 if문을 활용해 특정 시간대에만 코드를 실행하는 방법을 단계별로 알려드리겠습니다.
왜 시간 기반 실행이 필요할까요?
업무 자동화, 정기 알림, 데이터 수집 등 다양한 상황에서 특정 시간에만 프로그램을 실행해야 하는 경우가 많습니다. 예를 들어 출근 알림, 주식 시장 개장 알림, 일일 리포트 전송 등이 있습니다.
기본 구조 이해하기
datetime 모듈로 현재 시간 가져오기
Python에서 시간을 다루려면 datetime 모듈을 사용합니다. 현재 시간을 확인하는 기본 코드는 다음과 같습니다.
from datetime import datetime
current_time = datetime.now()
print(f"현재 시간: {current_time}")
print(f"현재 시각: {current_time.hour}시 {current_time.minute}분")
datetime.now() 함수는 현재 날짜와 시간 정보를 모두 담고 있는 객체를 반환합니다. 여기서 hour 속성으로 시간을, minute 속성으로 분을 추출할 수 있습니다.
if문으로 시간 범위 지정하기
시간대 범위 설정 방법
특정 시간대에만 코드를 실행하려면 if문과 비교 연산자를 조합합니다. 가장 기본적인 형태는 다음과 같습니다.
from datetime import datetime
current_time = datetime.now()
# 오전 6시부터 9시 사이인지 확인
if 6 <= current_time.hour <= 9:
print("좋은 아침입니다!")
이 코드는 현재 시간이 오전 6시 이상, 9시 이하일 때만 메시지를 출력합니다. 파이썬의 연쇄 비교 문법을 사용해 간결하게 작성할 수 있습니다.
다양한 시간 조건 예시
업무 시간대만 실행하기:
# 평일 업무 시간 (9시~18시)
if 9 <= current_time.hour < 18:
print("업무 시간입니다")
특정 시간에만 실행하기:
# 정확히 12시에만 실행
if current_time.hour == 12 and current_time.minute == 0:
print("점심시간입니다")
저녁 시간대 확인하기:
# 오후 6시 이후
if current_time.hour >= 18:
print("퇴근 시간입니다")
텔레그램 봇 자동화 실전 예제
봇 설정 및 기본 코드
텔레그램 봇을 활용한 시간 기반 알림 시스템을 만들어보겠습니다. 먼저 python-telegram-bot 라이브러리를 설치해야 합니다.
import telegram
from datetime import datetime
# 텔레그램 봇 설정
token = '여기에_봇_토큰_입력'
bot = telegram.Bot(token=token)
chat_id = '여기에_채팅ID_입력'
# 현재 시간 확인
current_time = datetime.now()
# 아침 시간대(6~9시) 알림
if 6 <= current_time.hour <= 9:
bot.sendMessage(chat_id=chat_id, text='좋은 아침입니다 😍')
보안을 위한 토큰 관리
실제 운영 환경에서는 토큰을 코드에 직접 작성하지 않는 것이 좋습니다. 환경 변수나 별도 설정 파일을 사용하세요.
import os
from dotenv import load_dotenv
load_dotenv()
token = os.getenv('TELEGRAM_BOT_TOKEN')
chat_id = os.getenv('TELEGRAM_CHAT_ID')
여러 시간대 알림 설정하기
하루 중 여러 시간대에 다른 메시지를 보내는 방법입니다.
from datetime import datetime
import telegram
token = '봇_토큰'
bot = telegram.Bot(token=token)
chat_id = '채팅ID'
current_time = datetime.now()
hour = current_time.hour
# 시간대별 메시지 전송
if 6 <= hour <= 9:
bot.sendMessage(chat_id=chat_id, text='좋은 아침입니다 🌅')
elif 12 <= hour <= 13:
bot.sendMessage(chat_id=chat_id, text='점심시간입니다 🍽️')
elif 18 <= hour <= 20:
bot.sendMessage(chat_id=chat_id, text='저녁 식사 하셨나요? 🌙')
요일별 조건 추가하기
평일과 주말 구분하기
업무일에만 알림을 받고 싶다면 요일 조건을 추가합니다.
from datetime import datetime
current_time = datetime.now()
weekday = current_time.weekday() # 0:월요일, 6:일요일
# 평일(월~금) 오전 9시 알림
if 0 <= weekday <= 4 and current_time.hour == 9:
print("출근 시간입니다")
# 주말 확인
if weekday >= 5:
print("즐거운 주말 보내세요")
특정 요일에만 실행하기
# 월요일에만 실행
if weekday == 0 and 9 <= current_time.hour < 10:
bot.sendMessage(chat_id=chat_id, text='월요일 화이팅! 💪')
# 금요일 오후에만 실행
if weekday == 4 and current_time.hour >= 18:
bot.sendMessage(chat_id=chat_id, text='불금 되세요! 🎉')
자동 실행 설정 방법
윈도우 작업 스케줄러 활용
코드를 작성했다면 자동으로 실행되도록 설정해야 합니다. 윈도우에서는 작업 스케줄러를 사용합니다.
- 작업 스케줄러 실행 (Windows + R → taskschd.msc)
- 기본 작업 만들기 선택
- 트리거에서 실행 주기 설정 (매일, 매주 등)
- 동작에서 Python 스크립트 경로 지정
리눅스 Cron 설정
리눅스나 맥OS에서는 cron을 사용합니다.
# crontab 편집
crontab -e
# 매 시간마다 실행
0 * * * * /usr/bin/python3 /경로/스크립트.py
# 매일 오전 6시 실행
0 6 * * * /usr/bin/python3 /경로/스크립트.py
# 평일 오전 9시 실행
0 9 * * 1-5 /usr/bin/python3 /경로/스크립트.py
실전 활용 팁
에러 처리 추가하기
안정적인 운영을 위해 예외 처리를 추가하세요.
import telegram
from datetime import datetime
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
try:
current_time = datetime.now()
if 6 <= current_time.hour <= 9:
token = '봇_토큰'
bot = telegram.Bot(token=token)
bot.sendMessage(chat_id='채팅ID', text='좋은 아침입니다')
logger.info("메시지 전송 성공")
except Exception as e:
logger.error(f"오류 발생: {str(e)}")
실행 로그 기록하기
언제 코드가 실행되었는지 기록하면 디버깅에 유용합니다.
from datetime import datetime
def send_morning_message():
current_time = datetime.now()
with open('실행로그.txt', 'a', encoding='utf-8') as f:
f.write(f"{current_time}: 메시지 전송 시도\\n")
if 6 <= current_time.hour <= 9:
# 메시지 전송 코드
with open('실행로그.txt', 'a', encoding='utf-8') as f:
f.write(f"{current_time}: 메시지 전송 완료\\n")
타임존 처리하기
해외 서버를 사용한다면 타임존 설정이 필요합니다.
from datetime import datetime
import pytz
# 한국 시간대 설정
korea_tz = pytz.timezone('Asia/Seoul')
current_time = datetime.now(korea_tz)
if 6 <= current_time.hour <= 9:
print("한국 시간 기준 아침입니다")
성능 최적화 방법
불필요한 실행 줄이기
매번 봇 객체를 생성하는 대신 조건을 먼저 확인하세요.
from datetime import datetime
current_time = datetime.now()
# 시간 조건을 먼저 확인
if 6 <= current_time.hour <= 9:
# 조건이 맞을 때만 봇 초기화
import telegram
token = '봇_토큰'
bot = telegram.Bot(token=token)
bot.sendMessage(chat_id='채팅ID', text='좋은 아침입니다')
중복 실행 방지하기
같은 시간에 여러 번 실행되는 것을 방지하는 방법입니다.
from datetime import datetime
import os
def check_already_sent():
today = datetime.now().date()
log_file = 'last_sent.txt'
if os.path.exists(log_file):
with open(log_file, 'r') as f:
last_sent = f.read().strip()
if last_sent == str(today):
return True
with open(log_file, 'w') as f:
f.write(str(today))
return False
current_time = datetime.now()
if 6 <= current_time.hour <= 9 and not check_already_sent():
# 메시지 전송
print("오늘 첫 메시지 전송")
자주 묻는 질문
정확한 시각(예: 06:00:00)에만 실행하려면?
분과 초까지 확인하는 조건을 추가하세요.
if current_time.hour == 6 and current_time.minute == 0 and current_time.second == 0:
print("정확히 6시입니다")
시간 범위가 자정을 넘어가면?
자정을 넘어가는 시간 범위는 or 연산자를 사용합니다.
# 밤 11시부터 새벽 2시까지
if current_time.hour >= 23 or current_time.hour <= 2:
print("심야 시간대입니다")
여러 스크립트를 시간차를 두고 실행하려면?
분 단위 조건을 추가하거나 time.sleep()을 사용하세요.
import time
if current_time.hour == 9:
# 9시 정각
send_first_message()
time.sleep(1800) # 30분 대기
send_second_message()
마무리하며
Python의 datetime 모듈과 if문을 활용하면 시간 기반 자동화를 쉽게 구현할 수 있습니다. 텔레그램 봇뿐만 아니라 이메일 전송, 데이터 백업, 웹 스크래핑 등 다양한 작업에 응용할 수 있습니다.
처음에는 단순한 시간 조건부터 시작해서 점차 요일, 타임존, 에러 처리 등을 추가하면 더욱 안정적인 자동화 시스템을 만들 수 있습니다. 여러분의 일상을 편리하게 만들어줄 자동화 프로그램을 직접 만들어보세요!
참고 자료
- Python 공식 문서 – datetime 모듈: https://docs.python.org/ko/3/library/datetime.html
- Python Telegram Bot 공식 문서: https://python-telegram-bot.readthedocs.io/
- Crontab 사용법 가이드: https://crontab.guru/
관련 글
- Python 자동화 완벽 가이드: 업무 시간 절약하는 7가지 방법
- 텔레그램 봇 만들기 초보자 가이드
- Python 스케줄러 라이브러리 비교: Schedule vs APScheduler