Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any python library for parsing dates and times from a natural language? [closed]

I'm looking for a way to translate 'tomorrow at 6am' or 'next monday at noon' to the appropriate datetime objects.

I thought of engineering a complex set of rules, but is there another way?

like image 893
Vasil Avatar asked Sep 29 '09 23:09

Vasil


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.

Which package is used to work with date and time in Python?

Python Datetime module comes built into Python, so there is no need to install it externally. Python Datetime module supplies classes to work with date and time. These classes provide a number of functions to deal with dates, times and time intervals.

What is Timedelta in Python?

Python timedelta class. The timedelta is a class in datetime module that represents duration. The delta means average of difference and so the duration expresses the difference between two date, datetime or time instances. By using timedelta, you may estimate the time for future and past.


2 Answers

parsedatetime - Python module that is able to parse 'human readable' date/time expressions.

#!/usr/bin/env python from datetime import datetime import parsedatetime as pdt # $ pip install parsedatetime  cal = pdt.Calendar() now = datetime.now() print("now: %s" % now) for time_string in ["tomorrow at 6am", "next moday at noon",                      "2 min ago", "3 weeks ago", "1 month ago"]:    print("%s:\t%s" % (time_string, cal.parseDT(time_string, now)[0])) 

Output

now: 2015-10-18 13:55:29.732131 tomorrow at 6am:    2015-10-19 06:00:00 next moday at noon: 2015-10-18 12:00:00 2 min ago:  2015-10-18 13:53:29 3 weeks ago:    2015-09-27 13:55:29 1 month ago:    2015-09-18 13:55:29 
like image 119
Alex Barrett Avatar answered Oct 12 '22 10:10

Alex Barrett


See what you think of this example from the pyparsing wiki. It handles the following test cases:

today tomorrow yesterday in a couple of days a couple of days from now a couple of days from today in a day 3 days ago 3 days from now a day ago now 10 minutes ago 10 minutes from now in 10 minutes in a minute in a couple of minutes 20 seconds ago in 30 seconds 20 seconds before noon 20 seconds before noon tomorrow noon midnight noon tomorrow 6am tomorrow 0800 yesterday 12:15 AM today 3pm 2 days from today a week from today a week from now 3 weeks ago noon next Sunday noon Sunday noon last Sunday 
like image 37
PaulMcG Avatar answered Oct 12 '22 10:10

PaulMcG