|
| 1 | +--- |
| 2 | +layout: post |
| 3 | +title: "Python timestamp 값 얻기 - 현재시간, 변환, 활용법 완벽 가이드" |
| 4 | +date: 2025-06-04 14:30:00 +0900 |
| 5 | +categories: [Development, Python] |
| 6 | +tags: [python, timestamp, time, datetime, database, beginner] |
| 7 | +author: "Kevin Park" |
| 8 | +excerpt: "Python에서 timestamp 값을 얻고 변환하는 방법부터 실제 프로젝트 활용까지. 바로 사용 가능한 코드 예시와 함께 설명합니다." |
| 9 | +--- |
| 10 | + |
| 11 | +# Python timestamp 값 얻기 - 현재시간, 변환, 활용법 완벽 가이드 |
| 12 | + |
| 13 | +## 🎯 핵심 해결책 (바로 사용 가능) |
| 14 | + |
| 15 | +### 가장 많이 사용되는 패턴 |
| 16 | + |
| 17 | +```python |
| 18 | +import time |
| 19 | + |
| 20 | +# 1. 현재 timestamp 얻기 (소수점 포함) |
| 21 | +timestamp = time.time() |
| 22 | +print(timestamp) |
| 23 | +# 출력: 1717484200.256982 |
| 24 | + |
| 25 | +# 2. 정수형 timestamp 얻기 (가장 많이 사용) |
| 26 | +timestamp_int = int(time.time()) |
| 27 | +print(timestamp_int) |
| 28 | +# 출력: 1717484200 |
| 29 | + |
| 30 | +# 3. 밀리초 단위 timestamp (JavaScript 호환) |
| 31 | +timestamp_ms = int(time.time() * 1000) |
| 32 | +print(timestamp_ms) |
| 33 | +# 출력: 1717484200256 |
| 34 | +``` |
| 35 | + |
| 36 | +### 실무에서 자주 사용하는 변환 |
| 37 | + |
| 38 | +```python |
| 39 | +from datetime import datetime |
| 40 | + |
| 41 | +# 4. datetime을 timestamp로 변환 |
| 42 | +dt = datetime.now() |
| 43 | +timestamp_from_dt = int(dt.timestamp()) |
| 44 | + |
| 45 | +# 5. timestamp를 datetime으로 변환 |
| 46 | +dt_from_timestamp = datetime.fromtimestamp(timestamp_int) |
| 47 | +print(dt_from_timestamp) |
| 48 | +# 출력: 2025-06-04 14:30:00 |
| 49 | + |
| 50 | +# 6. 특정 날짜의 timestamp 얻기 |
| 51 | +specific_date = datetime(2025, 12, 25, 0, 0, 0) |
| 52 | +christmas_timestamp = int(specific_date.timestamp()) |
| 53 | +``` |
| 54 | + |
| 55 | +### 데이터베이스 저장용 포맷 |
| 56 | + |
| 57 | +```python |
| 58 | +# DynamoDB, MongoDB 등에서 사용 |
| 59 | +db_timestamp = { |
| 60 | + 'created_at': int(time.time()), |
| 61 | + 'updated_at': int(time.time()) |
| 62 | +} |
| 63 | + |
| 64 | +# MySQL, PostgreSQL 등에서 사용 |
| 65 | +sql_datetime = datetime.now().strftime('%Y-%m-%d %H:%M:%S') |
| 66 | +``` |
| 67 | + |
| 68 | +--- |
| 69 | + |
| 70 | +## 📚 상세 설명 |
| 71 | + |
| 72 | +### 배경 및 필요성 |
| 73 | + |
| 74 | +Timestamp는 특정 시점을 숫자로 표현하는 방법으로, 1970년 1월 1일 00:00:00 UTC부터 경과한 초의 수를 나타냅니다. 개발에서 timestamp가 필요한 주요 상황들: |
| 75 | + |
| 76 | +- **데이터베이스 저장**: 생성/수정 시간 기록 |
| 77 | +- **API 통신**: 시간 데이터 교환 |
| 78 | +- **로그 관리**: 이벤트 발생 시간 추적 |
| 79 | +- **캐시 만료**: TTL(Time To Live) 설정 |
| 80 | +- **성능 측정**: 실행 시간 계산 |
| 81 | + |
| 82 | +### 다양한 timestamp 생성 방법 |
| 83 | + |
| 84 | +#### 1. time 모듈 사용 |
| 85 | + |
| 86 | +```python |
| 87 | +import time |
| 88 | + |
| 89 | +# 현재 시간의 timestamp (float) |
| 90 | +current_time = time.time() |
| 91 | +print(f"Float timestamp: {current_time}") |
| 92 | + |
| 93 | +# 정수형으로 변환 (초 단위) |
| 94 | +int_timestamp = int(current_time) |
| 95 | +print(f"Integer timestamp: {int_timestamp}") |
| 96 | + |
| 97 | +# 밀리초 단위 (JavaScript와 호환) |
| 98 | +ms_timestamp = int(current_time * 1000) |
| 99 | +print(f"Millisecond timestamp: {ms_timestamp}") |
| 100 | +``` |
| 101 | + |
| 102 | +#### 2. datetime 모듈 사용 |
| 103 | + |
| 104 | +```python |
| 105 | +from datetime import datetime, timezone |
| 106 | + |
| 107 | +# 현재 시간의 timestamp |
| 108 | +now = datetime.now() |
| 109 | +timestamp = int(now.timestamp()) |
| 110 | + |
| 111 | +# UTC 시간으로 변환 |
| 112 | +utc_now = datetime.now(timezone.utc) |
| 113 | +utc_timestamp = int(utc_now.timestamp()) |
| 114 | + |
| 115 | +# 특정 날짜의 timestamp |
| 116 | +specific_date = datetime(2025, 1, 1, 0, 0, 0) |
| 117 | +new_year_timestamp = int(specific_date.timestamp()) |
| 118 | +``` |
| 119 | + |
| 120 | +### 실제 활용 사례 |
| 121 | + |
| 122 | +#### 1. DynamoDB TTL 설정 |
| 123 | + |
| 124 | +```python |
| 125 | +import time |
| 126 | + |
| 127 | +def create_session_data(user_id, session_data, expire_hours=24): |
| 128 | + """세션 데이터를 DynamoDB에 저장 (TTL 설정)""" |
| 129 | + ttl = int(time.time()) + (expire_hours * 3600) # 24시간 후 만료 |
| 130 | + |
| 131 | + item = { |
| 132 | + 'user_id': user_id, |
| 133 | + 'session_data': session_data, |
| 134 | + 'created_at': int(time.time()), |
| 135 | + 'ttl': ttl # DynamoDB가 자동으로 삭제 |
| 136 | + } |
| 137 | + return item |
| 138 | + |
| 139 | +# 사용 예시 |
| 140 | +session = create_session_data('user123', {'login': True}) |
| 141 | +print(session) |
| 142 | +``` |
| 143 | + |
| 144 | +#### 2. API 로그 시간 기록 |
| 145 | + |
| 146 | +```python |
| 147 | +import time |
| 148 | +import json |
| 149 | + |
| 150 | +def log_api_request(endpoint, method, response_time): |
| 151 | + """API 요청 로그 기록""" |
| 152 | + log_entry = { |
| 153 | + 'timestamp': int(time.time()), |
| 154 | + 'endpoint': endpoint, |
| 155 | + 'method': method, |
| 156 | + 'response_time_ms': response_time, |
| 157 | + 'date_readable': datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S') |
| 158 | + } |
| 159 | + |
| 160 | + # 로그 파일에 저장 |
| 161 | + with open('api_logs.json', 'a') as f: |
| 162 | + f.write(json.dumps(log_entry) + '\n') |
| 163 | + |
| 164 | +# 사용 예시 |
| 165 | +log_api_request('/api/users', 'GET', 150) |
| 166 | +``` |
| 167 | + |
| 168 | +#### 3. 성능 측정 |
| 169 | + |
| 170 | +```python |
| 171 | +import time |
| 172 | + |
| 173 | +def measure_execution_time(func): |
| 174 | + """함수 실행 시간 측정 데코레이터""" |
| 175 | + def wrapper(*args, **kwargs): |
| 176 | + start_time = time.time() |
| 177 | + result = func(*args, **kwargs) |
| 178 | + end_time = time.time() |
| 179 | + |
| 180 | + execution_time = end_time - start_time |
| 181 | + print(f"{func.__name__} 실행 시간: {execution_time:.4f}초") |
| 182 | + return result |
| 183 | + return wrapper |
| 184 | + |
| 185 | +@measure_execution_time |
| 186 | +def slow_function(): |
| 187 | + time.sleep(2) # 2초 대기 |
| 188 | + return "완료" |
| 189 | + |
| 190 | +# 사용 예시 |
| 191 | +slow_function() |
| 192 | +# 출력: slow_function 실행 시간: 2.0021초 |
| 193 | +``` |
| 194 | + |
| 195 | +### 시간대 처리 및 변환 |
| 196 | + |
| 197 | +```python |
| 198 | +from datetime import datetime, timezone |
| 199 | +import pytz |
| 200 | + |
| 201 | +# UTC timestamp 생성 |
| 202 | +utc_now = datetime.now(timezone.utc) |
| 203 | +utc_timestamp = int(utc_now.timestamp()) |
| 204 | + |
| 205 | +# 한국 시간으로 변환 |
| 206 | +kst = pytz.timezone('Asia/Seoul') |
| 207 | +kst_time = datetime.fromtimestamp(utc_timestamp, tz=kst) |
| 208 | + |
| 209 | +# 다양한 시간대의 timestamp |
| 210 | +timezones = { |
| 211 | + 'UTC': timezone.utc, |
| 212 | + 'KST': pytz.timezone('Asia/Seoul'), |
| 213 | + 'PST': pytz.timezone('US/Pacific'), |
| 214 | + 'EST': pytz.timezone('US/Eastern') |
| 215 | +} |
| 216 | + |
| 217 | +for tz_name, tz in timezones.items(): |
| 218 | + local_time = datetime.now(tz) |
| 219 | + timestamp = int(local_time.timestamp()) |
| 220 | + print(f"{tz_name}: {timestamp} ({local_time.strftime('%Y-%m-%d %H:%M:%S %Z')})") |
| 221 | +``` |
| 222 | + |
| 223 | +### 에러 처리 및 예외 상황 |
| 224 | + |
| 225 | +```python |
| 226 | +from datetime import datetime |
| 227 | + |
| 228 | +def safe_timestamp_conversion(date_string, format_string='%Y-%m-%d %H:%M:%S'): |
| 229 | + """안전한 날짜 문자열을 timestamp로 변환""" |
| 230 | + try: |
| 231 | + dt = datetime.strptime(date_string, format_string) |
| 232 | + return int(dt.timestamp()) |
| 233 | + except ValueError as e: |
| 234 | + print(f"날짜 형식 오류: {e}") |
| 235 | + return None |
| 236 | + except Exception as e: |
| 237 | + print(f"예상치 못한 오류: {e}") |
| 238 | + return None |
| 239 | + |
| 240 | +# 사용 예시 |
| 241 | +valid_date = "2025-06-04 14:30:00" |
| 242 | +invalid_date = "2025-13-40 25:70:70" |
| 243 | + |
| 244 | +print(safe_timestamp_conversion(valid_date)) # 정상 변환 |
| 245 | +print(safe_timestamp_conversion(invalid_date)) # None 반환 |
| 246 | +``` |
| 247 | + |
| 248 | +### 유용한 헬퍼 함수들 |
| 249 | + |
| 250 | +```python |
| 251 | +import time |
| 252 | +from datetime import datetime |
| 253 | + |
| 254 | +class TimestampHelper: |
| 255 | + """Timestamp 관련 유틸리티 클래스""" |
| 256 | + |
| 257 | + @staticmethod |
| 258 | + def now(): |
| 259 | + """현재 timestamp (정수)""" |
| 260 | + return int(time.time()) |
| 261 | + |
| 262 | + @staticmethod |
| 263 | + def now_ms(): |
| 264 | + """현재 timestamp (밀리초)""" |
| 265 | + return int(time.time() * 1000) |
| 266 | + |
| 267 | + @staticmethod |
| 268 | + def to_readable(timestamp): |
| 269 | + """timestamp를 읽기 쉬운 형태로 변환""" |
| 270 | + return datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S') |
| 271 | + |
| 272 | + @staticmethod |
| 273 | + def days_ago(days): |
| 274 | + """N일 전의 timestamp""" |
| 275 | + return int(time.time() - (days * 24 * 3600)) |
| 276 | + |
| 277 | + @staticmethod |
| 278 | + def days_later(days): |
| 279 | + """N일 후의 timestamp""" |
| 280 | + return int(time.time() + (days * 24 * 3600)) |
| 281 | + |
| 282 | +# 사용 예시 |
| 283 | +helper = TimestampHelper() |
| 284 | + |
| 285 | +print(f"현재: {helper.now()}") |
| 286 | +print(f"현재 (ms): {helper.now_ms()}") |
| 287 | +print(f"읽기 쉬운 형태: {helper.to_readable(helper.now())}") |
| 288 | +print(f"7일 전: {helper.days_ago(7)}") |
| 289 | +print(f"30일 후: {helper.days_later(30)}") |
| 290 | +``` |
| 291 | + |
| 292 | +## 결론 |
| 293 | + |
| 294 | +Python에서 timestamp를 다루는 것은 개발의 기본이지만, 실제 프로젝트에서는 시간대 처리, 데이터베이스 저장, API 통신 등 다양한 상황을 고려해야 합니다. 이 포스트에서 제공한 코드 예시들을 참고하여 여러분의 프로젝트에 적합한 방식을 선택하시기 바랍니다. |
| 295 | + |
| 296 | +**핵심 포인트**: |
| 297 | +- 대부분의 경우 `int(time.time())`으로 충분 |
| 298 | +- 데이터베이스 저장 시 정수형 timestamp 권장 |
| 299 | +- 시간대가 중요한 경우 UTC 기준으로 저장 |
| 300 | +- 에러 처리를 통한 안전한 변환 구현 |
| 301 | + |
| 302 | +**다음 단계**: |
| 303 | +- Django나 Flask에서의 timestamp 활용 |
| 304 | +- 시계열 데이터베이스와 timestamp |
| 305 | +- 마이크로서비스 간 시간 동기화 방법 |
0 commit comments