2019년 8월 14일 수요일

Timezone 관련하여 Arrow를 사용한 예제

Timezone 관련하여 Arrow를 사용한 예제

우선 장고의 datetime 필드가 utc로 저장되어있기 때문에 그것을 local time으로 전환해야 한다. 하지만 python 기본 라이브러리로는 조금 쉽지 않다.

따라서 Arrow를 쓰면 조금 편한 듯


import arrow
from dateutil import tz
"""
socialite 의 Report라는 모델을 예제로 이용함.

Report의 created 필드는 datetime Field로써 UTC로 시간 값을 저장한다. 
"""
rt = Report.object.get(pk=109)
# create Arrow Instance from datetime
created_utc = arrow.get(rt.created, tz.gettz('UTC'))
# convert Arrow instance to about 'Asia/Seoul'
created_at_seoul = created_utc.to('Asia/Seoul')

무척이나 쉽다.

번환함수를 만들어봤다.


def convert_to_seoul(utc_created):
    arrow_utc = arrow.get(utc_created, tz.gettz('UTC'))
    created_to_seoul = arrow_utc.to('Asia/Seoul')
    # created_to_seoul 은 Arrow instance 이기 때문에 datetime으로 변환이 필요하다. 
    return created_to_seoul.datetime.isoformat()

댓글 없음:

댓글 쓰기