1

What is the best way to convert the following date pattern to a datetime.date object in Python?

1st April
8th April
15th April
1st May
Jeff LaFay
  • 12,882
  • 13
  • 71
  • 101
Joseph Victor Zammit
  • 14,760
  • 10
  • 76
  • 102
  • 1
    I thought of inelegant solutions, such as removing the "st", "nd", "rd" and "th" suffix through a regex and then parsing via `strptime()`. Anyone has something better in mind? – Joseph Victor Zammit Apr 12 '12 at 18:21

2 Answers2

4

dateutil.parser will parse almost every known date format:

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

To always get a date in the future:

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)
mensi
  • 9,580
  • 2
  • 34
  • 43
  • Can you set the `parse` method to always return a future date? E.g. if it's `1st April` can it return `01-04-2013` instead of `01-04-2012`? – Joseph Victor Zammit Apr 12 '12 at 18:39
  • @JosvicZammit you can supply a datetime instance with default values in the default kwarg: `parse('8th April', default=datetime.date(2013, 1, 1))` – mensi Apr 12 '12 at 18:43
  • @mensi, I think a default doesn't work because the problem is more complicated. – Mark Ransom Apr 12 '12 at 18:50
  • If you give a default date with a nonsense year, you can check the result and replace the nonsense with the current year; then if the result is less than today, add a year. – Mark Ransom Apr 12 '12 at 18:53
  • @MarkRansom I adjusted my answer to hopefully solve it in a clean way – mensi Apr 12 '12 at 18:57
  • @mensi Doesn't work, however you did answer the original question. Will put a new question about this. Maybe someone knows an "elegant way" to do it. – Joseph Victor Zammit Apr 12 '12 at 18:58
  • @mensi New question [here](http://stackoverflow.com/questions/10130091/default-future-year-when-effecting-date-conversion-with-dateutil). – Joseph Victor Zammit Apr 12 '12 at 19:20
0
from datetime import datetime

val = val.replace('th', '').replace('st', '')
d = datetime.strptime(val, '%d %B')
Rustem
  • 2,884
  • 1
  • 17
  • 32