[python] 일반 형식으로 날짜를 인쇄하는 방법은 무엇입니까?

이것은 내 코드입니다.

import datetime
today = datetime.date.today()
print(today)

이것은 2008-11-22정확히 내가 원하는 것입니다.

그러나 나는 이것을 추가하고있는 목록을 가지고 있으며 갑자기 모든 것이 “삐걱 거리는”것입니다. 코드는 다음과 같습니다.

import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print(mylist)

다음이 인쇄됩니다.

[datetime.date(2008, 11, 22)]

어떻게 간단한 데이트를 할 수 2008-11-22있습니까?



답변

왜 : 날짜는 객체입니다

파이썬에서 날짜는 객체입니다. 따라서, 그것들을 조작 할 때, 타임 스탬프 나 어떤 것도 아닌 문자열이 아닌 객체를 조작합니다.

파이썬의 모든 객체에는 두 개의 문자열 표현이 있습니다.

  • “print”가 사용하는 정규 표현은 str()함수를 사용하여 얻을 수 있습니다 . 대부분의 경우 사람이 읽을 수있는 가장 일반적인 형식이며 표시를 쉽게하는 데 사용됩니다. 그래서 str(datetime.datetime(2008, 11, 22, 19, 53, 42))당신에게 제공합니다 '2008-11-22 19:53:42'.

  • 객체의 특성을 나타내는 데 사용되는 대체 표현입니다 (데이터). 그것은 사용하여 얻을 수있는 repr()기능을하고 개발하거나 디버깅하는 동안 어떤 데이터를 어떤 사용자의 조작 알고 편리합니다. repr(datetime.datetime(2008, 11, 22, 19, 53, 42))당신에게 제공합니다 'datetime.datetime(2008, 11, 22, 19, 53, 42)'.

“print”를 사용하여 날짜를 인쇄 str()하면 멋진 날짜 문자열을 볼 수 있습니다. 그러나 인쇄 할 때 mylist객체 목록을 인쇄했으며 Python은을 사용하여 데이터 세트를 나타내려고했습니다 repr().

어떻게 : 당신은 그걸로 하시겠습니까?

날짜를 조작 할 때는 날짜 개체를 계속 사용하십시오. 그들은 수천 가지 유용한 메소드를 얻었으며 대부분의 Python API는 날짜가 객체 일 것으로 예상합니다.

표시하려면을 사용하십시오 str(). 파이썬에서는 모든 것을 명시 적으로 캐스팅하는 것이 좋습니다. 인쇄 할 때가되면을 사용하여 날짜의 문자열 표현을 얻으십시오 str(date).

마지막 한가지. 날짜를 인쇄하려고 할 때 인쇄했습니다 mylist. 날짜를 인쇄하려면 컨테이너 (목록)가 아닌 날짜 개체를 인쇄해야합니다.

EG, 당신은 목록에 모든 날짜를 인쇄하려고합니다 :

for date in mylist :
    print str(date)

참고 특정 경우에 , 당신은 심지어 생략 할 수 있습니다 str()인쇄는 당신을 위해 그것을 사용하기 때문이다. 그러나 습관이되어서는 안됩니다 🙂

실제 사례, 코드 사용

import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist[0] # print the date object, not the container ;-)
2008-11-22

# It's better to always use str() because :

print "This is a new day : ", mylist[0] # will work
>>> This is a new day : 2008-11-22

print "This is a new day : " + mylist[0] # will crash
>>> cannot concatenate 'str' and 'datetime.date' objects

print "This is a new day : " + str(mylist[0])
>>> This is a new day : 2008-11-22

고급 날짜 형식

날짜는 기본 표현이지만 특정 형식으로 인쇄 할 수 있습니다. 이 경우 strftime()메서드를 사용하여 사용자 지정 문자열 표현을 얻을 수 있습니다 .

strftime() 날짜 형식을 지정하는 방법을 설명하는 문자열 패턴이 필요합니다.

EG :

print today.strftime('We are the %d, %b %Y')
>>> 'We are the 22, Nov 2008'

다음의 모든 문자 "%"는 무언가에 대한 형식을 나타냅니다.

  • %d 요일 번호입니다
  • %m 월 번호입니다
  • %b 월 약어입니다
  • %y 마지막 두 자리 연도
  • %Y 일년 내내

기타

공식 문서 를 보거나 McCutchen의 빠른 참조 를 통해 모든 것을 알 수는 없습니다.

이후 PEP3101 , 모든 객체는 문자열의 방법은 형식에 의해 자동으로 사용하는 고유의 형식을 가질 수 있습니다. 날짜 시간의 경우 형식은 strftime에서 사용 된 것과 동일합니다. 따라서 다음과 같이 위와 동일하게 수행 할 수 있습니다.

print "We are the {:%d, %b %Y}".format(today)
>>> 'We are the 22, Nov 2008'

이 형식의 장점은 다른 개체를 동시에 변환 할 수 있다는 것입니다. 형식화 된 문자열 리터럴 (Python 3.6, 2016-12-23부터)을
도입하면 다음과 같이 작성할 수 있습니다.

import datetime
f"{datetime.datetime.now():%Y-%m-%d}"
>>> '2017-06-15'

현지화

올바른 방식으로 사용하면 날짜가 현지 언어와 문화에 자동으로 적응할 수 있지만 약간 복잡합니다. SO (Stack Overflow) ;-)에 대한 다른 질문이있을 수 있습니다.


답변

import datetime
print datetime.datetime.now().strftime("%Y-%m-%d %H:%M")

편집하다:

Cees 제안 후, 나는 또한 시간을 사용하기 시작했습니다.

import time
print time.strftime("%Y-%m-%d %H:%M")


답변

date, datetime 및 time 객체는 모두 명시 적 형식 문자열을 제어하여 시간을 나타내는 문자열을 만들기 위해 strftime (format) 메서드를 지원합니다.

다음은 지시문과 의미가있는 형식 코드 목록입니다.

    %a  Locales abbreviated weekday name.
    %A  Locales full weekday name.
    %b  Locales abbreviated month name.
    %B  Locales full month name.
    %c  Locales appropriate date and time representation.
    %d  Day of the month as a decimal number [01,31].
    %f  Microsecond as a decimal number [0,999999], zero-padded on the left
    %H  Hour (24-hour clock) as a decimal number [00,23].
    %I  Hour (12-hour clock) as a decimal number [01,12].
    %j  Day of the year as a decimal number [001,366].
    %m  Month as a decimal number [01,12].
    %M  Minute as a decimal number [00,59].
    %p  Locales equivalent of either AM or PM.
    %S  Second as a decimal number [00,61].
    %U  Week number of the year (Sunday as the first day of the week)
    %w  Weekday as a decimal number [0(Sunday),6].
    %W  Week number of the year (Monday as the first day of the week)
    %x  Locales appropriate date representation.
    %X  Locales appropriate time representation.
    %y  Year without century as a decimal number [00,99].
    %Y  Year with century as a decimal number.
    %z  UTC offset in the form +HHMM or -HHMM.
    %Z  Time zone name (empty string if the object is naive).
    %%  A literal '%' character.

이것이 파이썬에서 날짜 및 시간 모듈로 할 수있는 일입니다

    import time
    import datetime

    print "Time in seconds since the epoch: %s" %time.time()
    print "Current date and time: ", datetime.datetime.now()
    print "Or like this: ", datetime.datetime.now().strftime("%y-%m-%d-%H-%M")


    print "Current year: ", datetime.date.today().strftime("%Y")
    print "Month of year: ", datetime.date.today().strftime("%B")
    print "Week number of the year: ", datetime.date.today().strftime("%W")
    print "Weekday of the week: ", datetime.date.today().strftime("%w")
    print "Day of year: ", datetime.date.today().strftime("%j")
    print "Day of the month : ", datetime.date.today().strftime("%d")
    print "Day of week: ", datetime.date.today().strftime("%A")

다음과 같은 내용이 인쇄됩니다.

    Time in seconds since the epoch:    1349271346.46
    Current date and time:              2012-10-03 15:35:46.461491
    Or like this:                       12-10-03-15-35
    Current year:                       2012
    Month of year:                      October
    Week number of the year:            40
    Weekday of the week:                3
    Day of year:                        277
    Day of the month :                  03
    Day of week:                        Wednesday


답변

date.strftime을 사용하십시오. 형식 인수는 설명서에 설명되어 있습니다 .

이것은 당신이 원하는 것입니다 :

some_date.strftime('%Y-%m-%d')

이것은 로케일을 고려합니다. (이 작업을 수행)

some_date.strftime('%c')


답변

이것은 더 짧습니다 :

>>> import time
>>> time.strftime("%Y-%m-%d %H:%M")
'2013-11-19 09:38'


답변

# convert date time to regular format.

d_date = datetime.datetime.now()
reg_format_date = d_date.strftime("%Y-%m-%d %I:%M:%S %p")
print(reg_format_date)

# some other date formats.
reg_format_date = d_date.strftime("%d %B %Y %I:%M:%S %p")
print(reg_format_date)
reg_format_date = d_date.strftime("%Y-%m-%d %H:%M:%S")
print(reg_format_date)

산출

2016-10-06 01:21:34 PM
06 October 2016 01:21:34 PM
2016-10-06 13:21:34


답변

또는

from datetime import datetime, date

"{:%d.%m.%Y}".format(datetime.now())

Out : ’25 .12.2013

또는

"{} - {:%d.%m.%Y}".format("Today", datetime.now())

Out : ‘오늘-25.12.2013’

"{:%A}".format(date.today())

아웃 : ‘수요일’

'{}__{:%Y.%m.%d__%H-%M}.log'.format(__name__, datetime.now())

아웃 : ‘__main ____ 2014.06.09__16-56.log’