python 将Jun改为June

0 投票
2 回答
1095 浏览
提问于 2025-04-18 09:20

我这样获取明天的日期:

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

结果是 2014年6月11日

我这样解析它:

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 呢?

在我的情况下,我会同时有 JunJune,所以我更希望把 Jun 改成 June,这样一切就能正常工作了。

2 个回答

1

你需要使用 %b 格式代码 来表示缩写的月份名称:

>>> 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)
>>>
5

我想我明白这个问题了。你不需要先把日期时间对象转换成字符串:

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

撰写回答