我明天的约会是这样的
tomorrow = datetime.date.today() + datetime.timedelta(days=1)
self.FirstDateString = str(tomorrow.strftime("%d %b %Y"))结果是11 Jun 2014
我像这样解析它:
datetime.strptime('11 Jun 2014', "%d %B %Y").date()我发现了一个错误:
ValueError: time data '11 Jun 2014' does not match format '%d %B %Y'但是,当我将Jun改为June时,它就能工作了。
那么,我如何告诉tomorrow = datetime.date.today() + datetime.timedelta(days=1)给我June而不是Jun
在我的情况下,我将有六月和六月,所以我宁愿把六月改为六月,使一切正常。
发布于 2014-06-10 19:14:41
我想我理解这个问题。您不需要首先将datetime对象转换为字符串:
import datetime
today = datetime.datetime.today()
print(datetime.datetime.strftime(today, '%d %b %Y'))
print(datetime.datetime.strftime(today, '%d %B %Y'))这将给你:
10 Jun 2014
10 June 2014现在,如果您的问题是您有一些字符串并想要转换它们,但是有些字符串具有Jun,而另一些字符串是June,那么您别无选择,只能尝试一种方式,如果它不起作用,尝试另一种方式:
try:
obj = datetime.datetime.strptime(some_string, '%d %b %Y')
except ValueError:
# It didn't work with %b, try with %B
try:
obj = datetime.datetime.strptime(some_string, '%d %B %Y')
except ValueError:
# Its not Jun or June, eeek!
raise ValueError("Date format doesn't match!")
print('The date is: {0.day} {0.month} {0.year}'.format(obj))发布于 2014-06-10 19:11:58
您需要对缩写的月份名称使用 format code:
>>> from datetime import datetime
>>>
>>> datetime.strptime('11 Jun 2014', "%d %B %Y").date()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python33\lib\_strptime.py", line 500, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "C:\Python33\lib\_strptime.py", line 337, in _strptime
(data_string, format))
ValueError: time data '11 Jun 2014' does not match format '%d %B %Y'
>>>
>>> datetime.strptime('11 Jun 2014', "%d %b %Y").date()
datetime.date(2014, 6, 11)
>>>https://stackoverflow.com/questions/24149057
复制相似问题