The problem. In my Django application, users create tasks for scheduled execution. The users are quite non-technical, and it would be great if they can write conventional human-readable expressions to define when to execute certain task, such as:
This is inspired by Todoist. For now, only dates are necessary; no times. I've spent a couple of hours googling for a library to do that, but with no luck. I am expecting a function, say, in_range(expression, date)
, such that:
>>> in_range('every monday, wednesday', date(2014, 4, 28))
True
>>> in_range('every end of month', date(2014, 5, 12))
False
>>> in_range('every millenium', date(2014, 5, 8))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: unknown token "millenium".
Variants. That's what I've looked through.
datetime
library does date parsing, but not date range parsing as per above.rrule
, very functional, but still does not support parsing.So, is there a Python code snippet, or a library that I missed, to do the thing? If not, I'm going to write the parser myself. Would like to release it in open source if it appears to be not too bad.
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.
dateparser provides modules to easily parse localized dates in almost any string formats commonly found on web pages.
A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.
Recurrent is a library that will do natural language date parsing with support for recurring dates. It doesn't match the API you provided, but allows you to create rules that can be used with Python's datetime
library.
From their Github page:
Natural language parsing of dates and recurring events
Examples
Date times
- next tuesday
- tomorrow
- in an hour
Recurring events
- on weekdays
- every fourth of the month from jan 1 2010 to dec 25th 2020
- each thurs until next month
- once a year on the fourth thursday in november
- tuesdays and thursdays at 3:15
Messy strings
- Please schedule the meeting for every other tuesday at noon
- Set an alarm for next tuesday at 11pm
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