如何以常规格式打印日期?
这是我的代码:
import datetime
today = datetime.date.today()
print(today)
这段代码输出了:2008-11-22
,正是我想要的结果。
但是,我有一个列表,我把这个结果加到列表里,结果突然一切都变得“奇怪”了。这里是代码:
import datetime
mylist = [datetime.date.today()]
print(mylist)
这段代码输出了 [datetime.date(2008, 11, 22)]
。我该怎么才能只得到一个简单的日期,比如 2008-11-22
呢?
26 个回答
date
、datetime
和time
这些对象都有一个叫做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
import datetime
print datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
编辑:
在听了Cees的建议后,我也开始使用时间了:
import time
print time.strftime("%Y-%m-%d %H:%M")
为什么:日期是对象
在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()
来表示这组数据。
如何:你想用它做什么?
当你操作日期时,记得一直使用日期对象。它们有成千上万的有用方法,而且大多数Python的API都期望日期是对象。
当你想要显示日期时,只需使用str()
。在Python中,好的做法是明确地转换所有东西。所以在打印时,使用str(date)
来获取日期的字符串表示。
最后一点,当你尝试打印日期时,你打印的是mylist
。如果你想打印一个日期,你必须打印日期对象,而不是它们的容器(列表)。
例如,如果你想打印列表中的所有日期:
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()
需要一个字符串模式,说明你想如何格式化日期。
例如:
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位数字)
等等。
可以查看官方文档,或者McCutchen的快速参考,你不可能记住所有。
自从PEP3101以来,每个对象都可以有自己的格式,自动用于任何字符串的format方法。在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'
本地化
如果你以正确的方式使用日期,它们可以自动适应当地的语言和文化,但这有点复杂。也许可以在Stack Overflow上提出另一个问题 ;-)