如何在Python中以常规格式打印日期? [英] How to print date in a regular format in Python?

查看:143
本文介绍了如何在Python中以常规格式打印日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

  import datetime 
today = datetime.date.today()
打印今天

这打印:2008-11-22这正是我想要的...我有一个列表我附加到,然后突然,一切都变得愚蠢。这是代码:

  import datetime 
mylist = []
today = datetime.date.today ()
mylist.append(今天)
打印mylist

以下:

  [datetime.date(2008,11,22)] 
/ pre>

如何在2008-11-22之类的简单日期中获得?

解决方案

WHY:dates是对象



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




发生了什么事,当你有使用打印打印日期,它使用 str(),所以你可以看到一个很好的日期字符串。但是当您打印 mylist 时,您打印了一个对象列表,并尝试使用 repr()



如何:你该怎么做?



你操纵日期,继续使用日期对象。他们获得了数千种有用的方法,大部分Python API都希望日期为对象。



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



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



EG,要打印列表中的所有日期:


 在mylist中的日期:
print str(date)

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



使用代码

的实际情况

 code> import datetime 
mylist = []
today = datetime.date.today()
mylist.append(今)
打印mylist [0]#打印日期对象,而不是容器;-)
2008-11-22

#最好总是使用str(),因为:

print这是一个新的一天:,mylist [0]#将工作
这是一个新的一天:2008-11-22

打印这是一个新的一天:+ mylist [0]#将崩溃
无法连接'str'和'datetime.date'对象

print这是一个新的一天:+ str(mylist [0])
这是一个新日:2008-11-22



高级日期格式



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



strftime()期望一个字符串模式解释你想要格式化你的日期。



EG:

  print today.strftime('我们是%d,%b%Y')
'我们是2008年11月22日的'

之后的所有字母表示格式对于某些东西:




  • %d 是日数

  • %m 是月号

  • %b 是月缩写

  • %y 是最后两位数字

  • %Y 是全年





查看官方文档 McCutchen的qui ck参考你不能全部了解它们。



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

  print我们是{:%d,%b%Y} .format(今天)
'我们是2008年11月22日的'

这个表单是你也可以同时转换其他对象。



本地化



日期可以自动适应当地语言和文化,如果你使用正确的方式,但有点复杂。也许对于另一个问题(堆栈溢出); - )


This is my code:

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

This prints: 2008-11-22 which is exactly what I want BUT....I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:

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

This prints the following:

[datetime.date(2008, 11, 22)]

How on earth can I get just a simple date like "2008-11-22"?

解决方案

The WHY: dates are objects

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

Any object in Python have 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.

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

这篇关于如何在Python中以常规格式打印日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆