How to print a date in a regular format?

后端 未结 22 2803
孤街浪徒
孤街浪徒 2020-11-21 23:00

This is my code:

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

This prints: 2008-11-22 which is exactly what I wa

相关标签:
22条回答
  • 2020-11-21 23:47

    The WHY: dates are objects

    In Python, dates are objects. Therefore, when you manipulate them, you manipulate objects, not strings or timestamps.

    Any object in Python has TWO string representations:

    • The regular representation that is used by print can be get using the str() function. It is most of the time the most common human readable format and is used to ease display. So str(datetime.datetime(2008, 11, 22, 19, 53, 42)) gives you '2008-11-22 19:53:42'.

    • The alternative representation that is used to represent the object nature (as a data). It can be get using the repr() function and is handy to know what kind of data your manipulating while you are developing or debugging. repr(datetime.datetime(2008, 11, 22, 19, 53, 42)) gives you 'datetime.datetime(2008, 11, 22, 19, 53, 42)'.

    What happened is that when you have printed the date using print, it used str() so you could see a nice date string. But when you have printed mylist, you have printed a list of objects and Python tried to represent the set of data, using repr().

    The How: what do you want to do with that?

    Well, when you manipulate dates, keep using the date objects all long the way. They got thousand of useful methods and most of the Python API expect dates to be objects.

    When you want to display them, just use str(). In Python, the good practice is to explicitly cast everything. So just when it's time to print, get a string representation of your date using str(date).

    One last thing. When you tried to print the dates, you printed mylist. If you want to print a date, you must print the date objects, not their container (the list).

    E.G, you want to print all the date in a list :

    for date in mylist :
        print str(date)
    

    Note that in that specific case, you can even omit str() because print will use it for you. But it should not become a habit :-)

    Practical case, using your code

    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
    

    Advanced date formatting

    Dates have a default representation, but you may want to print them in a specific format. In that case, you can get a custom string representation using the strftime() method.

    strftime() expects a string pattern explaining how you want to format your date.

    E.G :

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

    All the letter after a "%" represent a format for something :

    • %d is the day number
    • %m is the month number
    • %b is the month abbreviation
    • %y is the year last two digits
    • %Y is the all year

    etc

    Have a look at the official documentation, or McCutchen's quick reference you can't know them all.

    Since PEP3101, every object can have its own format used automatically by the method format of any string. In the case of the datetime, the format is the same used in strftime. So you can do the same as above like this:

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

    The advantage of this form is that you can also convert other objects at the same time.
    With the introduction of Formatted string literals (since Python 3.6, 2016-12-23) this can be written as

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

    Localization

    Dates can automatically adapt to the local language and culture if you use them the right way, but it's a bit complicated. Maybe for another question on SO(Stack Overflow) ;-)

    0 讨论(0)
  • 2020-11-21 23:47
    from datetime import date
    def time-format():
      return str(date.today())
    print (time-format())
    

    this will print 6-23-2018 if that's what you want :)

    0 讨论(0)
  • 2020-11-21 23:48

    Simple answer -

    datetime.date.today().isoformat()
    
    0 讨论(0)
  • 2020-11-21 23:50

    You can use easy_date to make it easy:

    import date_converter
    my_date = date_converter.date_to_string(today, '%Y-%m-%d')
    
    0 讨论(0)
  • 2020-11-21 23:50

    I don't fully understand but, can use pandas for getting times in right format:

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

    And:

    >>> 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']
    

    But it's storing strings but easy to convert:

    >>> l=list(map(str,l))
    >>> list(map(pd.to_datetime,l))
    [Timestamp('2018-10-07 00:00:00')]
    
    0 讨论(0)
  • 2020-11-21 23:52
    import datetime
    print datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
    

    Edit:

    After Cees' suggestion, I have started using time as well:

    import time
    print time.strftime("%Y-%m-%d %H:%M")
    
    0 讨论(0)
提交回复
热议问题