我有一个日期字符串的格式为“Mon Feb 15 2010”。我想更改格式为'15/02/2010'。我该怎么做呢?


当前回答

@ coding和@user1767754:下面两行可以工作。我看到没有人贴出被问到的例子问题的完整解决方案。希望这个解释足够了。

import datetime

x = datetime.datetime.strptime("Mon Feb 15 2010", "%a %b %d %Y").strftime("%d/%m/%Y")
print(x)

输出:

15/02/2010

其他回答

如果你不想定义输入日期格式,那么安装dateparser (pip Install dateparser)和,

from dateparser import parse
parse("Mon Feb 15 2010").strftime("%d/%m/%Y")

Datetime模块可以帮助你:

datetime.datetime.strptime(date_string, format1).strftime(format2)

对于具体的例子

>>> import datetime
>>> datetime.datetime.strptime('Mon Feb 15 2010', '%a %b %d %Y').strftime('%d/%m/%Y')
'15/02/2010'
>>>
>>> from_date="Mon Feb 15 2010"
>>> import time                
>>> conv=time.strptime(from_date,"%a %b %d %Y")
>>> time.strftime("%d/%m/%Y",conv)
'15/02/2010'

只是为了完成:在使用strptime()解析日期时,如果日期包含日期、月份等名称,请注意必须考虑区域设置。

在文档中也有脚注。

举个例子:

import locale
print(locale.getlocale())

>> ('nl_BE', 'ISO8859-1')

from datetime import datetime
datetime.strptime('6-Mar-2016', '%d-%b-%Y').strftime('%Y-%m-%d')

>> ValueError: time data '6-Mar-2016' does not match format '%d-%b-%Y'

locale.setlocale(locale.LC_ALL, 'en_US')
datetime.strptime('6-Mar-2016', '%d-%b-%Y').strftime('%Y-%m-%d')

>> '2016-03-06'

使用datetime库 http://docs.python.org/library/datetime.html查看9.1.7。 特别是strptime() strftime()行为¶ 例子 http://pleac.sourceforge.net/pleac_python/datesandtimes.html