使用strptime()转换日期

时间:2012-04-12 18:14:18

标签: python datetime

在Python中将以下日期模式转换为datetime.date对象的最佳方法是什么?

1st April
8th April
15th April
1st May

2 个答案:

答案 0 :(得分:4)

dateutil.parser将解析几乎所有已知的日期格式:

from dateutil.parser import parse
parse('8th April')

总是要在将来获得约会:

from dateutil.parser import parse
from datetime import datetime

d = parse('8th April')
if (d - datetime.now()).days <= 0:
    d = datetime.date(d.year+1, d.month, d.day)

答案 1 :(得分:0)

from datetime import datetime

val = val.replace('th', '').replace('st', '')
d = datetime.strptime(val, '%d %B')