这是我的代码:

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中,日期是对象。因此,当您操纵它们时,您操纵的是对象,而不是字符串或时间戳。

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

打印使用的正则表示可以使用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。

发生的情况是,当您使用print打印日期时,它使用str(),这样您可以看到一个漂亮的日期字符串。但是当您打印mylist时,您已经打印了一个对象列表,Python试图使用repr()表示数据集。

你想怎么做?

好吧,当你操纵日期时,一直使用日期对象。他们得到了数千种有用的方法,大多数Python API都希望日期是对象。

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

最后一件事。当你试图打印日期时,你打印了我的列表。如果要打印日期,必须打印日期对象,而不是其容器(列表)。

例如,您要打印列表中的所有日期:

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

例如:

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位数)

etc.

看看官方文件或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'

本地化

如果你用正确的方式,约会可以自动适应当地的语言和文化,但这有点复杂。可能是关于SO(堆栈溢出)的另一个问题;-)

其他回答

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.

这是我们可以使用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

简单的答案-

datetime.date.today().isoformat()

使用date.strftime。文档中描述了格式参数。

这是你想要的:

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

这一次考虑了Locale。(这样做)

some_date.strftime('%c')

我的答案是一个简短的免责声明——我只学了大约2周的Python,所以我绝不是专家;因此,我的解释可能不是最好的,我可能使用了不正确的术语。不管怎样,这就是答案。

我在代码中注意到,当您声明变量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。

我讨厌为了方便而导入太多模块的想法。我宁愿使用可用的模块,在本例中是datetime,而不是调用新的模块time。

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