Python相当于PHP的日期()

For simple formats its easy to come up with equivalents

PHP:

date("Y-m-d") === "2012-07-25";

Python:

date.strftime("%Y-%m-%d") == "2012-07-25"

But what is the Python equivalent of

date("jS F Y") === "25th July 2012";

I'm afraid I think you'll have to work the suffix out yourself:

>>> t = time.localtime()
>>> suffix = 'st' if t.tm_mday in [1,21,31] else 'nd' if t.tm_mday in [2, 22] else 'rd' if t.tm_mday in [3, 23] else 'th'
>>> time.strftime('%d%%s %B %Y', t) % suffix
'25th July 2012'

It's a bit English-centric for a programming language feature, so you can see why they didn't include it.

*Edited to add the "rd" suffix for 3rd and 23rd.

import datetime
print datetime.datetime.now().strftime("%dth %B %Y")

For more details see http://docs.python.org/library/datetime.html#strftime-strptime-behavior

The standard library only supports the standard C library strftime formatting codes, which are rather weak when it comes to localization. %B gives you the full month name in the locale your program is running under; if that's the English locale it'll give you 'April', but it could just as well give you 'Avril' if you are running on a french computer.

For web applications, you really want to use an external library like Babel to do that instead; Babel provides you with extra routines for formatting python datetime instances in different languages:

>>> from babel.dates import format_date
>>> format_date(d, format='long', locale='en')
u'April 1, 2007'

where format='long' is defined as a language-specific pattern.

Babel uses the Unicode Locale Data markup language to define these patterns giving you access to large pre-defined locale libraries that define these patters for you. Note that the grammatically correct way is to use cardinal, not ordinal numbers when formatting dates; British English allows for both ordinal and cardinal dates. As such the Unicode standard does not include ordinal post-fixes for dates.