복붙노트

[PYTHON] 정규 형식으로 날짜를 인쇄하는 방법은 무엇입니까?

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"와 같은 단순한 날짜를 얻을 수 있습니까?

해결법

  1. ==============================

    1.파이썬에서 날짜는 객체입니다. 따라서 사용자가 조작 할 때 문자열이 아니라 시간 소인이 아닌 객체를 조작합니다.

    파이썬에서 날짜는 객체입니다. 따라서 사용자가 조작 할 때 문자열이 아니라 시간 소인이 아닌 객체를 조작합니다.

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

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

    글쎄, 당신이 날짜를 조작 할 때, 날짜 객체를 모두 길게 계속 사용하라. 그들은 수천 가지 유용한 메소드를 가지며 Python API의 대부분은 날짜가 객체라고 기대합니다.

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

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

    E.G, 모든 날짜를 목록에 인쇄하고 싶습니다.

    for date in mylist :
        print str(date)
    

    그 특별한 경우에는 print가 그것을 사용하기 때문에 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 ()은 날짜 서식 지정 방법을 설명하는 문자열 패턴을 필요로합니다.

    예 :

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

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

    기타

    공식 문서를 보거나 McCutchen의 빠른 참조를 모두 알 수는 없습니다.

    PEP3101 이후 모든 오브젝트는 모든 문자열의 메소드 형식에 의해 자동으로 사용되는 자체 형식을 가질 수 있습니다. datetime의 경우 형식은 다음과 같이 동일합니다. 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'
    

    날짜를 올바르게 사용하면 날짜가 현지 언어와 문화에 자동으로 적응할 수 있지만 약간 복잡합니다. 어쩌면 다른 질문에 대한 (스택 오버플로) ;-)

  2. ==============================

    2.

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

    편집하다:

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

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

    3.date, datetime 및 time 객체는 모두 strftime (형식) 메서드를 지원하며, 명시적인 형식의 제어하에 시간을 나타내는 문자열을 만드는 것 끈.

    date, datetime 및 time 객체는 모두 strftime (형식) 메서드를 지원하며, 명시적인 형식의 제어하에 시간을 나타내는 문자열을 만드는 것 끈.

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

        %a  Locale’s abbreviated weekday name.
        %A  Locale’s full weekday name.      
        %b  Locale’s abbreviated month name.     
        %B  Locale’s full month name.
        %c  Locale’s 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  Locale’s 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  Locale’s appropriate date representation.    
        %X  Locale’s 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.
    

    이것은 우리가 파이썬에서 datetime과 time 모듈로 할 수있는 것이다.

        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
    
  4. ==============================

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

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

    이것은 당신이 원한 것입니다 :

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

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

    some_date.strftime('%c')
    
  5. ==============================

    5.이것은 더 짧습니다 :

    이것은 더 짧습니다 :

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

    6.

    # 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
    
  7. ==============================

    7.또는

    또는

    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())
    

    Out : '수요일'

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

    없음 : '__main ____ 2014.06.09__16-56.log'

  8. ==============================

    8.간단한 대답 -

    간단한 대답 -

    datetime.date.today().isoformat()
    
  9. ==============================

    9.형식화 된 문자열 문자열 형식 (파이썬 3.6, 2016-12-23 이후) : (형식적 문자열 리터럴에서 str.format ()을 사용한 nk9의 답 참조)

    형식화 된 문자열 문자열 형식 (파이썬 3.6, 2016-12-23 이후) : (형식적 문자열 리터럴에서 str.format ()을 사용한 nk9의 답 참조)

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

    날짜 / 시간 형식 지시문은 형식 문자열 구문의 일부로 설명되지 않고 date, datetime 및 time의 strftime () 설명서에서 설명됩니다. 이 표준은 1989 C 표준을 기반으로하지만 Python 3.6부터 일부 ISO 8601 지시문을 포함합니다.

  10. ==============================

    10.날짜 시간 객체를 문자열로 변환해야합니다.

    날짜 시간 객체를 문자열로 변환해야합니다.

    다음 코드는 나를 위해 일했습니다 :

    import datetime
    collection = []
    dateTimeString = str(datetime.date.today())
    collection.append(dateTimeString)
    print collection
    

    더 이상 도움이 필요하면 알려주세요.

  11. ==============================

    11.문자열로 추가 할 수 있습니다?

    문자열로 추가 할 수 있습니다?

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

    12.넌 할 수있어:

    넌 할 수있어:

    mylist.append(str(today))
    
  13. ==============================

    13.

    from datetime import date
    def time-format():
      return str(date.today())
    print (time-format())
    

    그것이 원하는 경우 6-23-2018이 인쇄됩니다 :)

  14. ==============================

    14.원하는 것을 간단하게하기 위해 요청한 사실을 고려할 때 다음과 같이 할 수 있습니다.

    원하는 것을 간단하게하기 위해 요청한 사실을 고려할 때 다음과 같이 할 수 있습니다.

    import datetime
    str(datetime.date.today())
    
  15. ==============================

    15.오늘의 print는 여러분이 원하는 것을 반환하기 때문에 today 객체의 __str__ 함수가 찾고있는 문자열을 반환한다는 것을 의미합니다.

    오늘의 print는 여러분이 원하는 것을 반환하기 때문에 today 객체의 __str__ 함수가 찾고있는 문자열을 반환한다는 것을 의미합니다.

    그래서 mylist.append (오늘 .__ str __ ())를 할 수 있습니다.

  16. ==============================

    16.easy_date를 사용하면 쉽게 사용할 수 있습니다.

    easy_date를 사용하면 쉽게 사용할 수 있습니다.

    import date_converter
    my_date = date_converter.date_to_string(today, '%Y-%m-%d')
    
  17. ==============================

    17.내 답변에 대한 신속한 면책 조항 - 필자는 약 2 주 동안 파이썬을 배웠으므로 결코 전문가가 아닙니다. 그러므로 내 설명이 최선이 아니며 잘못된 용어를 사용할 수도 있습니다. 어쨌든, 여기 있습니다.

    내 답변에 대한 신속한 면책 조항 - 필자는 약 2 주 동안 파이썬을 배웠으므로 결코 전문가가 아닙니다. 그러므로 내 설명이 최선이 아니며 잘못된 용어를 사용할 수도 있습니다. 어쨌든, 여기 있습니다.

    귀하의 코드에서 오늘 변수를 선언했을 때 datetime.date.today ()에 변수에 내장 함수의 이름을 지정하는 것으로 나타났습니다.

    다음 코드 줄 mylist.append (오늘)가 목록을 추가 할 때 today ()를 추가하는 것보다는 today 변수의 값으로 이전에 설정했던 datetime.date.today () 문자열 전체를 추가했습니다.

    datetime 모듈로 작업 할 때 대부분의 코더가 사용하지 않는 간단한 해결책은 변수의 이름을 변경하는 것입니다.

    여기 내가 시도한 것이있다.

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

    yyyy-mm-dd를 인쇄합니다.

  18. ==============================

    18.다음과 같이 날짜를 (년 / 월 / 일)으로 표시하는 방법입니다.

    다음과 같이 날짜를 (년 / 월 / 일)으로 표시하는 방법입니다.

    from datetime import datetime
    now = datetime.now()
    
    print '%s/%s/%s' % (now.year, now.month, now.day)
    
  19. ==============================

    19.편의를 위해 너무 많은 모듈을 가져 오는 아이디어는 싫다. 차라리 새로운 모듈 시간을 호출하는 대신 datetime을 사용할 수있는 모듈로 작업하고 싶습니다.

    편의를 위해 너무 많은 모듈을 가져 오는 아이디어는 싫다. 차라리 새로운 모듈 시간을 호출하는 대신 datetime을 사용할 수있는 모듈로 작업하고 싶습니다.

    >>> a = datetime.datetime(2015, 04, 01, 11, 23, 22)
    >>> a.strftime('%Y-%m-%d %H:%M')
    '2015-04-01 11:23'
    
  20. ==============================

    20.나는 완전히 이해하지는 못했지만 올바른 형식으로 시간을 얻는 데 팬더를 사용할 수 있습니다.

    나는 완전히 이해하지는 못했지만 올바른 형식으로 시간을 얻는 데 팬더를 사용할 수 있습니다.

    >>> import pandas as pd
    >>> pd.to_datetime('now')
    Timestamp('2018-10-07 06:03:30')
    >>> print(pd.to_datetime('now'))
    2018-10-07 06:03:47
    >>> pd.to_datetime('now').date()
    datetime.date(2018, 10, 7)
    >>> print(pd.to_datetime('now').date())
    2018-10-07
    >>> 
    

    과:

    >>> l=[]
    >>> l.append(pd.to_datetime('now').date())
    >>> l
    [datetime.date(2018, 10, 7)]
    >>> map(str,l)
    <map object at 0x0000005F67CCDF98>
    >>> list(map(str,l))
    ['2018-10-07']
    

    그러나 문자열을 저장하고 있지만 변환하기 쉽습니다.

    >>> l=list(map(str,l))
    >>> list(map(pd.to_datetime,l))
    [Timestamp('2018-10-07 00:00:00')]
    
  21. ==============================

    21.

    import datetime
    import time
    
    months = ["Unknown","January","Febuary","Marchh","April","May","June","July","August","September","October","November","December"]
    datetimeWrite = (time.strftime("%d-%m-%Y "))
    date = time.strftime("%d")
    month= time.strftime("%m")
    choices = {'01': 'Jan', '02':'Feb','03':'Mar','04':'Apr','05':'May','06': 'Jun','07':'Jul','08':'Aug','09':'Sep','10':'Oct','11':'Nov','12':'Dec'}
    result = choices.get(month, 'default')
    year = time.strftime("%Y")
    Date = date+"-"+result+"-"+year
    print Date
    

    이 방법으로 다음 예제와 같은 형식의 날짜를 얻을 수 있습니다. 22-Jun-2017

  22. from https://stackoverflow.com/questions/311627/how-to-print-a-date-in-a-regular-format by cc-by-sa and MIT license