python改变君到六月

Mar*_*oli 0 python datetime python-2.7

我像这样接受明天的约会

tomorrow = datetime.date.today() + datetime.timedelta(days=1)
            self.FirstDateString = str(tomorrow.strftime("%d %b %Y"))
Run Code Online (Sandbox Code Playgroud)

结果是 11 Jun 2014

我像这样解析它:

datetime.strptime('11 Jun 2014', "%d %B %Y").date()
Run Code Online (Sandbox Code Playgroud)

我收到了这个错误:

ValueError: time data '11 Jun 2014' does not match format '%d %B %Y'
Run Code Online (Sandbox Code Playgroud)

但是当我改变JunJune,它会起作用.

那么,我怎么能告诉tomorrow = datetime.date.today() + datetime.timedelta(days=1)我给我June而不是Jun

在我的情况下,我将同时拥有Jun和June,所以我更愿意将Jun改为6月以使一切正常

Bur*_*lid 5

我想我理解这个问题.您不需要首先将datetime对象转换为字符串:

import datetime
today = datetime.datetime.today()
print(datetime.datetime.strftime(today, '%d %b %Y'))
print(datetime.datetime.strftime(today, '%d %B %Y'))
Run Code Online (Sandbox Code Playgroud)

这会给你:

10 Jun 2014
10 June 2014
Run Code Online (Sandbox Code Playgroud)

现在,如果你的问题是你有一些字符串并希望转换它们,但有些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))
Run Code Online (Sandbox Code Playgroud)