【问题标题】:How to print a date in a regular format?如何以常规格式打印日期?
【发布时间】:2010-09-23 14:55:06
【问题描述】:

这是我的代码:

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 这样的简单日期?

【问题讨论】:

标签: python datetime date


【解决方案1】:

为什么:日期是对象

在 Python 中,日期是对象。因此,当您操作它们时,您操作的是对象,而不是字符串或时间戳。

Python 中的任何对象都有两种字符串表示形式:

  • 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() 来表示数据集。

The How:你想用它做什么?

好吧,当您操作日期时,请一直使用日期对象。他们获得了数千种有用的方法,并且大多数 Python API 都希望日期是对象。

当你想显示它们时,只需使用str()。在 Python 中,好的做法是显式转换所有内容。因此,当需要打印时,使用str(date) 获取日期的字符串表示形式。

最后一件事。当您尝试打印日期时,您打印了mylist。如果要打印日期,则必须打印日期对象,而不是它们的容器(列表)。

E.G,你想打印列表中的所有日期:

for date in mylist :
    print str(date)

请注意,在特定情况下,您甚至可以省略 str(),因为 print 会为您使用它。但它不应该成为一种习惯:-)

实际案例,使用您的代码

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() 需要一个字符串模式来解释您希望如何格式化您的日期。

E.G:

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

"%" 之后的所有字母都代表某种格式:

  • %d 是日期编号(2 位数字,必要时以前导零作为前缀)
  • %m 是月份编号(2 位数字,必要时以前导零为前缀)
  • %b 是月份的缩写(3 个字母)
  • %B 是完整的月份名称(字母)
  • %y 是年份数字的缩写(最后 2 位数字)
  • %Y 是完整的年份编号(4 位数字)

等等

Have a look at the official documentationMcCutchen's quick reference 你不可能都知道。

PEP3101 开始,每个对象都可以有自己的格式,被任何字符串的方法格式自动使用。在日期时间的情况下,格式与 时间。所以你可以像上面一样做:

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

这种形式的好处是还可以同时转换其他对象。
随着 Formatted string literals 的引入(自 Python 3.6,2016-12-23 起),这可以写成

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

本地化

如果您以正确的方式使用日期,日期可以自动适应当地的语言和文化,但这有点复杂。也许关于 SO(Stack Overflow) 的另一个问题 ;-)

【讨论】:

  • 顺便说一句,python 中几乎所有数据类型都是一个类(不可变对象除外,但它们可以被子类化)stackoverflow.com/questions/865911/…
  • “几乎”是什么意思? str 和 int 有一个 class 属性,其中包含'type',因此它们本身也有类,因为它们是元类类型的实例。
  • 这正是术语的问题:type != class?,即具有类型属性(提供类型推断机制以限定对象)是否足够,或者实体应该表现为对象。我正在尝试在这里为自己解决这个问题programmers.stackexchange.com/questions/164570/…
  • 如果你是一个类的实例,你就是一个对象。为什么需要它更复杂?
  • Python 中的每个值都是一个对象。每个对象都有一个类型。 "type" == "class" 正式(另请参阅 inspect.isclass 以确保)。人们倾向于对内置函数说“类型”,而对其他函数说“类”,但这并不重要
【解决方案2】:
import datetime
print datetime.datetime.now().strftime("%Y-%m-%d %H:%M")

编辑:

Cees' suggestion之后,我也开始使用时间了:

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

【讨论】:

  • 您可以使用datetime import datetime,然后是print datetime().now().strftime("%Y-%m-%d %H:%M")。只是语法不同。
  • from datetime import date; date.today().strftime("%Y-%m-%d") 对我来说仍然看起来很奇怪,但没有import time 是最好的。我认为 datetime 模块是用于日期数学的。
  • 我最喜欢的是from datetime import datetime as dt,现在我们可以和dt.now()一起玩了
【解决方案3】:

datedatetimetime 对象都支持 strftime(format) 方法, 在显式格式的控制下创建一个表示时间的字符串 字符串。

这是格式代码及其指令和含义的列表。

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

这就是我们可以用 Python 中的 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

【讨论】:

  • 这解决了我的问题,而“more-upvoted-answers”没有。但我的问题与 OP 不同。我想将月份打印为文本(“二月”而不是“2”)
【解决方案4】:

使用 date.strftime。格式化参数是described in the documentation

这是你想要的:

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

这一项考虑了语言环境。 (这样做)

some_date.strftime('%c')

【讨论】:

    【解决方案5】:

    这更短:

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

    【讨论】:

      【解决方案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】:

        甚至

        from datetime import datetime, date
        
        "{:%d.%m.%Y}".format(datetime.now())
        

        出:'25.12.2013

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

        出:“今天 - 2013 年 12 月 25 日”

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

        输出:“星期三”

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

        输出:'__main____2014.06.09__16-56.log'

        【讨论】:

          【解决方案8】:

          简单的答案 -

          datetime.date.today().isoformat()
          

          【讨论】:

            【解决方案9】:

            Formatted string literal 中使用特定类型的datetime 字符串格式(参见nk9's answer 使用str.format()。)(自Python 3.6,2016-12-23 起):

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

            日期/时间格式指令未记录为Format String Syntax 的一部分,而是记录在datedatetimetimestrftime() 文档中。它们基于 1989 C 标准,但包括自 Python 3.6 以来的一些 ISO 8601 指令。

            【讨论】:

            • 请注意,我也将此信息添加到已接受的answer
            • strftime 并不真正包含“ISO 8601 输出”。有“指令”,但仅限于特定标记,如“星期几”,而不是整个 ISO 8601 时间戳,我一直觉得这很烦人。
            【解决方案10】:

            我讨厌为了方便而导入太多模块的想法。我宁愿使用可用的模块,在这种情况下是datetime,而不是调用一个新模块time

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

            【讨论】:

            • 我认为通过a = datetime.datetime(2015, 04, 01, 23, 22).strftime('%Y-%m-%d %H:%M)在一行代码中做到这一点会更有效
            【解决方案11】:

            您需要将datetime 对象转换为str

            以下代码对我有用:

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

            如果您需要更多帮助,请告诉我。

            【讨论】:

            • 加油!不要鼓励新手存储字符串而不是日期对象。他将无法知道这是个好主意还是坏主意……
            • e-satis:如果您只需要一个字符串,那有什么大不了的?我们一直将固件构建日期存储为字符串 - 当您只需要一个简单的时间戳(YAGNI 和所有)时,有时存储整个对象是多余的。
            • 是的,在某些情况下确实如此。我的意思只是一个新手将无法识别这些案例。所以让我们从右脚开始:-)
            【解决方案12】:

            你可以这样做:

            mylist.append(str(today))
            

            【讨论】:

              【解决方案13】:

              考虑到您要求做一些简单的事情来做您想做的事,您可以:

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

              【讨论】:

                【解决方案14】:

                对于那些想要基于区域设置日期但不包括时间的人,请使用:

                >>> some_date.strftime('%x')
                07/11/2019
                

                【讨论】:

                  【解决方案15】:

                  由于print today 返回你想要的,这意味着今天对象的__str__ 函数返回你正在寻找的字符串。

                  所以你也可以使用mylist.append(today.__str__())

                  【讨论】:

                    【解决方案16】:
                    from datetime import date
                    
                    def today_in_str_format():
                        return str(date.today())
                    
                    print (today_in_str_format())
                    

                    如果这是你想要的,这将打印2018-06-23 :)

                    【讨论】:

                      【解决方案17】:

                      您可能希望将其附加为字符串?

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

                      【讨论】:

                        【解决方案18】:

                        您可以使用easy_date 来简化:

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

                        【讨论】:

                          【解决方案19】:

                          我的答案的快速免责声明 - 我只学习 Python 大约 2 周,所以我绝不是专家;因此,我的解释可能不是最好的,我可能会使用不正确的术语。不管怎样,就这样吧。

                          我在您的代码中注意到,当您声明变量 today = datetime.date.today() 时,您选择使用内置函数的名称来命名变量。

                          当您的下一行代码 mylist.append(today) 附加您的列表时,它附加了整个字符串 datetime.date.today(),您之前已将其设置为您的 today 变量的值,而不仅仅是附加 today()

                          一个简单的解决方案是更改变量的名称,尽管大多数编码人员在使用 datetime 模块时可能不会使用它。

                          这是我尝试过的:

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

                          它会打印出yyyy-mm-dd

                          【讨论】:

                            【解决方案20】:

                            以下是如何将日期显示为(年/月/日):

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

                            【讨论】:

                              【解决方案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

                              【讨论】:

                              • 太多的代码,你可以在一行中得到一些东西。使用%b,您将获得前三个月的单词,使用%B,您将获得整个月的单词。示例:datetime.datetime.now().strftime("%Y-%b-%d %H:%M:%S") 将返回 '2018-Oct-04 09:44:08'
                              【解决方案22】:

                              在 Python 中,您可以使用 datetime 模块中的 datetimedatetime 类中的 strftime() 方法格式化日期时间。

                              在您的特定情况下,您正在使用来自datetimedate 类。您可以使用以下 sn-p 将 today 变量格式化为格式为 yyyy-MM-dd 的字符串:

                              import datetime
                              
                              today = datetime.date.today()
                              print("formatted datetime: %s" % today.strftime("%Y-%m-%d"))
                              

                              下面是一个更完整的例子:

                              import datetime
                              today = datetime.date.today()
                              
                              # datetime in d/m/Y H:M:S format
                              date_time = today.strftime("%d/%m/%Y, %H:%M:%S")
                              print("datetime: %s" % date_time)
                              
                              # datetime in Y-m-d H:M:S format
                              date_time = today.strftime("%Y-%m-%d, %H:%M:%S")
                              print("datetime: %s" % date_time)
                              
                              # format date
                              date = today.strftime("%d/%m/%Y")
                              print("date: %s" % time)
                              
                              # format time
                              time = today.strftime("%H:%M:%S")
                              print("time: %s" % time)
                              
                              # day
                              day = today.strftime("%d")
                              print("day: %s" % day)
                              
                              # month
                              month = today.strftime("%m")
                              print("month: %s" % month)
                              
                              # year
                              year = today.strftime("%Y")
                              print("year: %s" % year)
                              
                              

                              更多指令:

                              来源:

                              【讨论】:

                                【解决方案23】:

                                我不完全理解,但可以使用 pandas 以正确的格式获取时间:

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

                                【讨论】:

                                • 一个完整的依赖来做某事 python std 库有方法要做?
                                猜你喜欢
                                • 1970-01-01
                                • 2014-11-29
                                • 1970-01-01
                                • 2013-11-10
                                • 2014-09-29
                                • 1970-01-01
                                • 2022-01-23
                                • 1970-01-01
                                相关资源
                                最近更新 更多