如何以常规格式打印日期?

Nom*_*ien 637 python datetime date

这是我的代码:

import datetime
today = datetime.date.today()
print today
Run Code Online (Sandbox Code Playgroud)

这打印:2008-11-22这正是我想要的但是......我有一个列表我正在追加这个然后突然一切都变得"不稳定".这是代码:

import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist
Run Code Online (Sandbox Code Playgroud)

这打印出以下内容:

[datetime.date(2008, 11, 22)]
Run Code Online (Sandbox Code Playgroud)

我怎么能得到像"2008-11-22"这样的简单日期呢?

e-s*_*tis 909

为什么:日期是对象

在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.如果要打印日期,则必须打印日期对象,而不是其容器(列表).

EG,您想要在列表中打印所有日期:

for date in mylist :
    print str(date)
Run Code Online (Sandbox Code Playgroud)

请注意,在这种特定情况下,您甚至可以省略,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
Run Code Online (Sandbox Code Playgroud)

高级日期格式

日期具有默认表示,但您可能希望以特定格式打印它们.在这种情况下,您可以使用该strftime()方法获取自定义字符串表示形式.

strftime() 期望一个字符串模式,解释您希望如何格式化日期.

EG:

print today.strftime('We are the %d, %b %Y')
>>> 'We are the 22, Nov 2008'
Run Code Online (Sandbox Code Playgroud)

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

  • %d 是天数
  • %m 是月份号码
  • %b 是月份缩写
  • %y 是最后两位数
  • %Y 是全年

等等

看看官方文档,或者McCutchen的快速参考,你无法全部了解它们.

PEP3101开始,每个对象都可以通过任何字符串的方法格式自动使用自己的格式.在datetime的情况下,格式与strftime中使用的格式相同.所以你可以像上面这样做:

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

此表单的优点是您还可以同时转换其他对象.
随着Formatted字符串文字的引入(自Python 3.6,2016-12-23),这可以写成

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

本土化

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

  • Python中的每个值都是一个对象.每个对象都有一个类型.["type"=="class"](http://stackoverflow.com/questions/4162578/python-terminology-class-vs-type)正式(另请参阅`inspect.isclass`以确保).人们倾向于对内置插件说"类型"而对其余部分说"类",但这并不重要 (9认同)
  • 这正是术语的问题:类型!=类?,即足以具有类型属性(提供类型推断机制来限定对象)或者实体应该作为对象行为.我想在这里为自己解决这个问题http://programmers.stackexchange.com/questions/164570/formal-definition-for-term-pure-oo-language (4认同)
  • BTW几乎python中的每个数据类型都是一个类(除了不可变,但它们可以是子类)http://stackoverflow.com/questions/865911/is-everything-an-object-in-python-like-ruby (3认同)

Dan*_*son 324

import datetime
print datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
Run Code Online (Sandbox Code Playgroud)

编辑:

在Cees建议之后,我也开始使用时间:

import time
print time.strftime("%Y-%m-%d %H:%M")
Run Code Online (Sandbox Code Playgroud)

  • `从日期时间导入日期; date.today().strftime("%Y-%m-%d")`对我来说看起来仍然是单声道的,但如果没有"导入时间",这是最好的.我认为datetime模块用于日期数学. (7认同)
  • `datetime.datetime`? (6认同)
  • 你可以使用`datetime import datetime`,然后`print datetime().now().strftime("%Y-%m-%d%H:%M")`.只有语法差异. (2认同)
  • 我最喜欢的是`from datetime import datetime as dt`,现在我们可以使用`dt.now()`了。 (2认同)

Tra*_*mer 150

日期,日期时间和时间对象都支持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.
Run Code Online (Sandbox Code Playgroud)

这就是我们可以用Python中的日期时间和时间模块做的事情

    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")
Run Code Online (Sandbox Code Playgroud)

那会打印出这样的东西:

    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
Run Code Online (Sandbox Code Playgroud)


Ali*_*har 73

使用date.strftime.格式化参数在文档描述.

这个是你想要的:

some_date.strftime('%Y-%m-%d')
Run Code Online (Sandbox Code Playgroud)

这个考虑了Locale.(做这个)

some_date.strftime('%c')
Run Code Online (Sandbox Code Playgroud)


Cee*_*man 35

这更短:

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


Waq*_*Ali 26

# 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)
Run Code Online (Sandbox Code Playgroud)

OUTPUT

2016-10-06 01:21:34 PM
06 October 2016 01:21:34 PM
2016-10-06 13:21:34
Run Code Online (Sandbox Code Playgroud)


b1_*_*b1_ 24

甚至

from datetime import datetime, date

"{:%d.%m.%Y}".format(datetime.now())
Run Code Online (Sandbox Code Playgroud)

出:'25 .12.2013

要么

"{} - {:%d.%m.%Y}".format("Today", datetime.now())
Run Code Online (Sandbox Code Playgroud)

出:'今天 - 25.12.2013'

"{:%A}".format(date.today())
Run Code Online (Sandbox Code Playgroud)

出:'星期三'

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

出:'__ main ____ 2014.06.09__16-56.log'


Fla*_*dun 13

简单回答 -

datetime.date.today().isoformat()
Run Code Online (Sandbox Code Playgroud)


han*_*dle 8

随着特定类型的datetime字符串格式(见NK9的答案使用str.format().)在格式化字符串字面量(因为Python 3.6,2016年12月23日):

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

日期/时间格式指令不会记录为部分格式字符串语法,而是在date,datetimetimestrftime()文档.它们基于1989 C标准,但包含自Python 3.6以来的一些ISO 8601指令.


ric*_*ydj 6

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

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


ntg*_*ntg 6

对于pandas.Timestamp s,可以使用strftime()例如:

utc_now = datetime.now()
Run Code Online (Sandbox Code Playgroud)

对于 iso 格式:

utc_now.isoformat()
Run Code Online (Sandbox Code Playgroud)

对于任何格式,例如:

utc_now.strftime("%m/%d/%Y, %H:%M:%S")
Run Code Online (Sandbox Code Playgroud)


Sim*_*son 5

您需要将日期时间对象转换为字符串。

以下代码为我工作:

import datetime
collection = []
dateTimeString = str(datetime.date.today())
collection.append(dateTimeString)
print collection
Run Code Online (Sandbox Code Playgroud)

让我知道您是否需要更多帮助。

  • 来吧 !不要鼓励新手存储字符串而不是日期对象。他不知道什么时候是个好主意... (3认同)
  • 是的,在某些情况下是这样。我只是说,新手将无法识别这些情况。因此,让我们从右脚开始:-) (3认同)

Dom*_*ano 5

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

\n

在您的具体情况下,您正在使用date中的类datetime。您可以使用以下代码片段将today\xc2\xa0 变量格式化为以下格式的字符串yyyy-MM-dd

\n
import datetime\n\ntoday = datetime.date.today()\nprint("formatted datetime: %s" % today.strftime("%Y-%m-%d"))\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n
import datetime\ntoday = datetime.date.today()\n\n# datetime in d/m/Y H:M:S format\ndate_time = today.strftime("%d/%m/%Y, %H:%M:%S")\nprint("datetime: %s" % date_time)\n\n# datetime in Y-m-d H:M:S format\ndate_time = today.strftime("%Y-%m-%d, %H:%M:%S")\nprint("datetime: %s" % date_time)\n\n# format date\ndate = today.strftime("%d/%m/%Y")\nprint("date: %s" % time)\n\n# format time\ntime = today.strftime("%H:%M:%S")\nprint("time: %s" % time)\n\n# day\nday = today.strftime("%d")\nprint("day: %s" % day)\n\n# month\nmonth = today.strftime("%m")\nprint("month: %s" % month)\n\n# year\nyear = today.strftime("%Y")\nprint("year: %s" % year)\n\n
Run Code Online (Sandbox Code Playgroud)\n

更多指令:

\n

1989 年 C 标准中的 Python strftime 指令

\n

资料来源:

\n\n