장고 - Datetime 학습

  • 이번 포스트에서는 특정 게시물이 업로드된 시점부터 현재까지 시간이 얼마나 흘렀는지 확인하는 방법에 대해 알아볼 것이다.

1. 앱의 하위 폴더로 templatetags 생성하여 원하는 기능을 구현할 함수 작성

ex) extore_project

  • 경로 : post[앱] > templatetags > calc.py

    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
    from django import template

    from datetime import datetime, date, timedelta


    register = template.Library()

    @register.filter
    def time_since(value):
    time_since = datetime.now() - value
    # 현재시간과의 차이가 1개월 이상일 경우
    if time_since > timedelta(days=30):
    return value.strftime("%Y.%m.%d")
    # 현재시간과의 차이가 24시간 이상일 경우
    if time_since > timedelta(days=1):
    return f'{time_since // timedelta(days=1)}일 전'
    # 현재시간과의 차이가 24시간 이하 1시간 이상일 경우
    elif time_since > timedelta(hours=1):
    return f'{time_since // timedelta(hours=1)}시간 전'
    # 현재시간과의 차이가 1시간 이하 1분 이상일 경우
    elif time_since > timedelta(minutes=1):
    return f'{time_since // timedelta(minutes=1)}분 전'
    # 현재시간과의 차이가 1분 이하 1초 이상일 경우
    elif time_since > timedelta(seconds=1):
    return f'{time_since // timedelta(seconds=1)}초 전'
    else:
    return '지금'
  • 코드 설명

    • 특정 html 파일에서 구현하고자 하는 기능(현재 시간 - 업로드한 게시물의 생성 시간)을 template tags를 이용하여 구현하였다.
    • 특정 게시물의 업로드한 시간을 value로 가정했을 때,
    • 현재시간 - 게시물 업로드한 시간은 time_since = datetime.now() - value 로 한다.
    • time_since(현재시간 - 게시물 업로드한 시간)를 원하는 단위의 시간으로 나누어 표현하고 싶은 결과를 확인할 수 있다.
    • 원하는 단위의 시간을 표현하기 위한 방법으로 timedelta를 사용할 수 있다.
    • time_since // timedelta(days=1)을 사용하여 며칠 전에 업로드한 게시물인지 확인할 수 있다.
    • time_since가 30일 이상이라면, strftime()를 이용하여 보여주고 싶은 날짜 표시
      • value.strftime(%Y.%m.%d) –> ex) 2019.06.25

2. html 파일에서 작성한 함수 호출

  • post(앱) > views.py

    1
    2
    3
    def post_list(request):
    posts = Post.objects.all()
    return render(request, 'post/post_list.html', {'object_list':posts})
  • post(앱) > templates > post > post_list.html

    1
    2
    3
    4
    5
    6
    7
    8
       ...
    {% for object in object_list %}
    ...
    {% load calc %}
    {{object.created|time_since}}
    <!-- ex) 1일 전/ 1시간 전/ 1분 전/ 1초 전/ 2019.06.25 -->
    ...
    {% endfor %}
  • 코드 설명

    • views.py에서 Post 객체들을 posts 변수로 설정한 뒤, post를 context data로 object_list로 설정
    • render함수를 사용하여 templates 폴더의 post/post_list.html 페이지로 이동
    • 해당 html 페이지에서 커스텀 템플릿 태그인 time_since를 사용하기 위해 ‘load calc’ 를 추가하고, 원하는 값으로 표현하고 싶은 변수에서 ‘|time_since’ 추가