developer tip

RFC 1123 파이썬에서 날짜 표현?

copycodes 2020. 11. 14. 10:45
반응형

RFC 1123 파이썬에서 날짜 표현?


datetime 객체를 RFC 1123 (HTTP / 1.1) 날짜 / 시간 문자열, 즉 형식의 문자열로 변환하는 매우 쉬운 방법이 있습니까?

Sun, 06 Nov 1994 08:49:37 GMT

strftime문자열이 로케일에 따라 다르기 때문에 사용 이 작동하지 않습니다. 줄을 손으로 만들어야합니까?


로케일 설정에 의존하지 않는 stdlib에서 wsgiref.handlers.format_date_time을 사용할 수 있습니다.

from wsgiref.handlers import format_date_time
from datetime import datetime
from time import mktime

now = datetime.now()
stamp = mktime(now.timetuple())
print format_date_time(stamp) #--> Wed, 22 Oct 2008 10:52:40 GMT

로케일 설정에 의존하지 않는 stdlib에서 email.utils.formatdate를 사용할 수 있습니다.

from email.utils import formatdate
from datetime import datetime
from time import mktime

now = datetime.now()
stamp = mktime(now.timetuple())
print formatdate(
    timeval     = stamp,
    localtime   = False,
    usegmt      = True
) #--> Wed, 22 Oct 2008 10:55:46 GMT

로케일 프로세스 전체를 설정할 수 있으면 다음을 수행 할 수 있습니다.

import locale, datetime

locale.setlocale(locale.LC_TIME, 'en_US')
datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')

로케일 프로세스 전체를 설정하지 않으려면 Babel 날짜 형식을 사용할 수 있습니다.

from datetime import datetime
from babel.dates import format_datetime

now = datetime.utcnow()
format = 'EEE, dd LLL yyyy hh:mm:ss'
print format_datetime(now, format, locale='en') + ' GMT'

wsgiref.handlers.format_date_time과 동일한 형식을 수동으로 지정하는 방법은 다음과 같습니다.

def httpdate(dt):
    """Return a string representation of a date according to RFC 1123
    (HTTP/1.1).

    The supplied date must be in UTC.

    """
    weekday = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][dt.weekday()]
    month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
             "Oct", "Nov", "Dec"][dt.month - 1]
    return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (weekday, dt.day, month,
        dt.year, dt.hour, dt.minute, dt.second)

Python 표준 이메일 모듈에서 formatdate () 함수를 사용할 수 있습니다.

from email.utils import formatdate
print formatdate(timeval=None, localtime=False, usegmt=True)

Gives the current time in the desired format:

Wed, 22 Oct 2008 10:32:33 GMT

In fact, this function does it "by hand" without using strftime()


If anybody reading this is working on a Django project, Django provides a function django.utils.http.http_date(epoch_seconds).

from django.utils.http import http_date

some_datetime = some_object.last_update
response['Last-Modified'] = http_date(some_datetime.timestamp())

You can set LC_TIME to force stftime() to use a specific locale:

>>> locale.setlocale(locale.LC_TIME, 'en_US')
'en_US'
>>> datetime.datetime.now().strftime(locale.nl_langinfo(locale.D_T_FMT))
'Wed 22 Oct 2008 06:05:39 AM '

Well, here is a manual function to format it:

def httpdate(dt):
    """Return a string representation of a date according to RFC 1123
    (HTTP/1.1).

    The supplied date must be in UTC.

    """
    weekday = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][dt.weekday()]
    month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
             "Oct", "Nov", "Dec"][dt.month - 1]
    return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (weekday, dt.day, month,
        dt.year, dt.hour, dt.minute, dt.second)

참고URL : https://stackoverflow.com/questions/225086/rfc-1123-date-representation-in-python

반응형