2017-08-29 73 views
-1

我有一个像23 July 1914这样的字符串,并且想将它转换为23/07/1914日期格式。 但我的代码给error如何将字符串转换为Python中的日期格式?

from datetime import datetime 
datetime_object = datetime.strptime('1 June 2005','%d %m %Y') 
print datetime_object 
+3

Python的错误是明确的(尽管Python 3在这一点上是一个很大的改进)。花一些时间仔细阅读错误:它应该清楚地指出错误。至少,你应该与我们分享这个错误。 –

回答

2

这里是你应该做的事情:

from datetime import datetime 
datetime_object = datetime.strptime('1 June 2005','%d %B %Y') 
s = datetime_object.strftime("%d/%m/%y") 
print(s) 

输出:

>>> 01/06/05 

你看你strptime需要两个参数。

strptime(string[, format]) 

和字符串将根据您指定的格式转换为datetime对象。

有各种格式

%a - abbreviated weekday name %A - full weekday name %b - abbreviated month name %B - full month name %c - preferred date and time representation %C - century number (the year divided by 100, range 00 to 99) %d - day of the month (01 to 31) %D - same as %m/%d/%y %e - day of the month (1 to 31) %g - like %G, but without the century %G - 4-digit year corresponding to the ISO week number (see %V). %h - same as %b %H - hour, using a 24-hour clock (00 to 23)

以上是一些例子。看看这里formats

请看看这两个!

%b - abbreviated month name %B - full month name

它应该与您提供的字符串类似。混淆看看这些例子。

>>> datetime.strptime('1 jul 2009','%d %b %Y') 
datetime.datetime(2009, 7, 1, 0, 0) 
>>> datetime.strptime('1 Jul 2009','%d %b %Y') 
datetime.datetime(2009, 7, 1, 0, 0) 
>>> datetime.strptime('jul 21 1996','%b %d %Y') 
datetime.datetime(1996, 7, 21, 0, 0) 

正如您所看到的基于格式的字符串转换为日期时间对象。现在看看!

>>> datetime.strptime('1 July 2009','%d %b %Y') 
Traceback (most recent call last): 
    File "<pyshell#12>", line 1, in <module> 
    datetime.strptime('1 July 2009','%d %b %Y') 
    File "/usr/lib/python3.5/_strptime.py", line 510, in _strptime_datetime 
    tt, fraction = _strptime(data_string, format) 
    File "/usr/lib/python3.5/_strptime.py", line 343, in _strptime 
    (data_string, format)) 
ValueError: time data '1 July 2009' does not match format '%d %b %Y' 

为什么错误,因为junJun(简称)代表%b。当你提供一个June它会感到困惑。现在该怎么办?改变了格式。

>>> datetime.strptime('1 July 2009','%d %B %Y') 
datetime.datetime(2009, 7, 1, 0, 0) 

现在简单地转换datetime对象很简单。

>>> s = datetime.strptime('1 July 2009','%d %B %Y') 
>>> s.strftime('%d/%m/%Y') 
'01/07/2009 

%m再次是在月(数字)显示它的格式阅读更多关于它们。

6

你的错误是你用来去掉字符串的格式。您使用%m作为月份的格式说明符,但是这需要一个0填充的整数来表示一年中的月份(例如,您的示例为06)。你想要使用的是%B,它预计一年中的一个月份会被完全写出(例如在你的例子中为June)。

有关datetime格式说明符的完整说明,请参阅the documentation,如果您有任何其他问题,请先在那里检查。

0

placeholder为“Month as locale's full name。”。将%B%m

>>> from datetime import datetime 
>>> datetime_object = datetime.strptime('1 June 2005','%d %B %Y') 
>>> print(datetime_object) 
2005-06-01 00:00:00 

>>> print(datetime_object.strftime("%d/%m/%Y")) 
01/06/2005 
0

这应该工作:

from datetime import datetime 
print(datetime.strptime('1 June 2005', '%d %B %Y').strftime('%d/%m/%Y')) 
print(datetime.strptime('23 July 1914', '%d %B %Y').strftime('%d/%m/%Y')) 

欲了解更多信息,你可以阅读有关strftime-strptime-behavior

0

%d的意思是“每月一零填充十进制数日“。

%m表示“月为零填充十进制数”。

您提供的日期或月份都不是您所期望的。您需要的月份%B(仅当您的语言环境为en_US时)和%-d

相关问题