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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With