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


当前回答

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

其他回答

将字符串转换为日期时间对象

from datetime import datetime
s = "2016-03-26T09:25:55.000Z"
f = "%Y-%m-%dT%H:%M:%S.%fZ"
out = datetime.strptime(s, f)
print(out)
output:
2016-03-26 09:25:55

您可以安装dateutil库。它的解析函数可以找出字符串的格式,而不必像使用datetime.strptime那样指定格式。

from dateutil.parser import parse
dt = parse('Mon Feb 15 2010')
print(dt)
# datetime.datetime(2010, 2, 15, 0, 0)
print(dt.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'

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

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