Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse human-format date ranges in Python

I have some human-style date ranges, in strings, like the following:

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

I want to parse these in Python so that I can end up with two datetime objects: one for the start, one for the end.

Is there any module that will let me do this? I've tried parsedatetime, and it looks like the evalRange function within that may do it (see http://code-bear.com/code/parsedatetime/docs/index.html for documentation), but it doesn't seem to parse anything at all, and just returns the current date/time, twice.

Any ideas?

like image 529
robintw Avatar asked Apr 26 '12 19:04

robintw


People also ask

How do you parse a date in python?

Python has a built-in method to parse dates, strptime . This example takes the string “2020–01–01 14:00” and parses it to a datetime object. The documentation for strptime provides a great overview of all format-string options.

What is date parser?

The Date. parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31). Only the ISO 8601 format ( YYYY-MM-DDTHH:mm:ss.


2 Answers

I ended up writing a Python module to do this, which I have now open-sourced. It is available for download on Github, there is documentation, and it can be installed from PyPI using:

pip install daterangeparser

For those who are interested, the module works by creating a full parser using PyParsing, a great (and remarkably easy-to-use) tool.

like image 132
robintw Avatar answered Oct 19 '22 11:10

robintw


You could use dateutil.parser. But it does not handle date ranges. You may need to apply a regular expression before.

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

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

Regards

like image 45
Francis Avatar answered Oct 19 '22 09:10

Francis