티스토리 뷰
파이썬을 이용하여 문자열을 datetime 형식으로 변경할 때 타임존을 명시적으로 설정하지 않으면 파이썬은 현재 서버의 기본 타임존을 자동으로 설정합니다.
모든 서버의 환경이 동일하다면 문제가 없지만, 운영과 테스트환경의 설정이 다른 경우 문제가 발생할 수 있습니다. 아래의 경우 동일한 코드를 실행하였지만 서버의 타임존이 달라서 다른 결과를 보여주고 있습니다.
--------------- 한국 타임존 -----------------
$ python3
Python 3.6.9 (default, Jan 26 2021, 15:33:00)
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> from datetime import datetime, timedelta, timezone
>>>
>>> created_text = "2022-05-10T08:23:51Z"
>>> created = datetime.strptime(created_text, "%Y-%m-%dT%H:%M:%SZ")
>>> created_unix_time = int(created.timestamp() * 1000)
>>> created_unix_time
1652138631000
--------------- UTC 타임존 -----------------
$ python3
Python 3.8.10 (default, May 12 2021, 15:56:47)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime, timedelta, timezone
>>>
>>> created_text = "2022-05-10T08:23:51Z"
>>> created = datetime.strptime(created_text, "%Y-%m-%dT%H:%M:%SZ")
>>> created_unix_time = int(created.timestamp() * 1000)
>>> created_unix_time
1652171031000
타임존을 설정하고 실행하면 다음과 같이 동일한 결과를 출력합니다.
------------ 한국 타임존 --------------
>>> from datetime import datetime, timedelta, timezone
>>>
>>> created_text = "2022-05-10T08:23:51Z"
>>> created = datetime.strptime(created_text, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)
>>> created_unix_time = int(created.timestamp() * 1000)
>>> created_unix_time
1652171031000
------------- UTC -------------------
>>> from datetime import datetime, timedelta, timezone
>>>
>>> created_text = "2022-05-10T08:23:51Z"
>>> created = datetime.strptime(created_text, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)
>>> created_unix_time = int(created.timestamp() * 1000)
>>> created_unix_time
1652171031000
파이썬을 이용하여 문자열을 datetime으로 변환할 때는 꼭 타임존을 입력하고 변경하는 것이 좋습니다.
반응형
'python' 카테고리의 다른 글
[python] requests 라이브러리에서 exceptions.MaxRetryError 가 발생하는 경우 처리 방법 (0) | 2022.05.17 |
---|---|
[python] http를 이용한 post 구현 (0) | 2022.05.17 |
[python] 우분투에 파이썬 3.7 설치 (0) | 2021.05.27 |
[python] pymysql 을 이용하여 db insert, update, select 하기 (0) | 2020.12.28 |
[python2] 출력된 유니코드를 한글로 확인하는 방법 (0) | 2020.12.08 |
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- Python
- ubuntu
- hbase
- 정올
- 다이나믹
- yarn
- bash
- java
- 하둡
- S3
- Linux
- SPARK
- 백준
- build
- HDFS
- oozie
- HIVE
- mysql
- 알고리즘
- emr
- Hadoop
- airflow
- 파이썬
- nodejs
- error
- Tez
- 하이브
- 오류
- SQL
- AWS
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함