Parse date ranges in Python format

I have date ranges in human style, in strings, for example:

22-24th April 2012
14-23 July
20th June - 5th July

I want to analyze them in Python so that in the end I can create two datetime objects: one for the beginning, one for the end.

Is there any module that will allow me to do this? I tried parsedatetimeand it looks like a function evalRangeinside that can do this (see http://code-bear.com/code/parsedatetime/docs/index.html for documentation), but it doesn’t parse anything and just returns the current one date / time twice.

Any ideas?

+5
source share
3 answers

Python, , open-sourced. Github, , PyPI,

pip install daterangeparser

, , , , PyParsing, ( ) .

+7

dateutil.parser. . , .

import dateutil.parser
dateutil.parser.parse("20th June")

datetime.datetime(2012, 6, 20, 0, 0)

+2

, :

  • , (: 20th June 5th July). (date_range == 22-24th July 2012) date_range.split(' ')[0].split('-'): ['22', '24th'] ( th ..)
  • datetime dateutil.parser: dateutil.parser.parse('22 July 2012')

:

import dateutil.parser
date_range = '20-22th July 2013'
date_range = date_range.lower()
for suffix in {'th', 'rd', 'st'}:
    date_range.replace(suffix, '')
days = date_range.split(' ')[0].split('-')
month_year = date_range.split(' ')[1]
begin, end = days[0] + ' ' + month_year, days[1] + ' ' + month_year
begin_date = dateutil.parser.parse(begin)
end_date = dateutil.parser.parse(end)
0

All Articles