summaryrefslogtreecommitdiff
path: root/examples/datetimeParseActions.py
diff options
context:
space:
mode:
authorPaul McGuire <ptmcg@users.noreply.github.com>2018-01-06 23:38:53 -0600
committerGitHub <noreply@github.com>2018-01-06 23:38:53 -0600
commit430c5ad767cc946e9da7cd5f4673a4e3bd135a3c (patch)
tree5a7df11e0fd52ab320b0ef3e670e260f315ca9ae /examples/datetimeParseActions.py
parentf1d12567a8da4d254e6d62bb0d650c87c7d0bb89 (diff)
parentd953150a6db3ac247a64b047edc2df7156f3e56b (diff)
downloadpyparsing-git-430c5ad767cc946e9da7cd5f4673a4e3bd135a3c.tar.gz
Merge pull request #1 from cngkaygusuz/master
Add Scrutinizer-CI configuration and other niceties
Diffstat (limited to 'examples/datetimeParseActions.py')
-rw-r--r--examples/datetimeParseActions.py68
1 files changed, 68 insertions, 0 deletions
diff --git a/examples/datetimeParseActions.py b/examples/datetimeParseActions.py
new file mode 100644
index 0000000..e42d2c6
--- /dev/null
+++ b/examples/datetimeParseActions.py
@@ -0,0 +1,68 @@
+# parseActions.py
+#
+# A sample program a parser to match a date string of the form "YYYY/MM/DD",
+# and return it as a datetime, or raise an exception if not a valid date.
+#
+# Copyright 2012, Paul T. McGuire
+#
+from datetime import datetime
+from pyparsing import *
+
+# define an integer string, and a parse action to convert it
+# to an integer at parse time
+integer = Word(nums).setName("integer")
+def convertToInt(tokens):
+ # no need to test for validity - we can't get here
+ # unless tokens[0] contains all numeric digits
+ return int(tokens[0])
+integer.setParseAction(convertToInt)
+# or can be written as one line as
+#integer = Word(nums).setParseAction(lambda t: int(t[0]))
+
+# define a pattern for a year/month/day date
+date_expr = integer('year') + '/' + integer('month') + '/' + integer('day')
+date_expr.ignore(pythonStyleComment)
+
+def convertToDatetime(s,loc,tokens):
+ try:
+ # note that the year, month, and day fields were already
+ # converted to ints from strings by the parse action defined
+ # on the integer expression above
+ return datetime(tokens.year, tokens.month, tokens.day).date()
+ except Exception as ve:
+ errmsg = "'%s/%s/%s' is not a valid date, %s" % \
+ (tokens.year, tokens.month, tokens.day, ve)
+ raise ParseException(s, loc, errmsg)
+date_expr.setParseAction(convertToDatetime)
+
+
+date_expr.runTests("""\
+ 2000/1/1
+
+ # invalid month
+ 2000/13/1
+
+ # 1900 was not a leap year
+ 1900/2/29
+
+ # but 2000 was
+ 2000/2/29
+ """)
+
+
+# if dates conform to ISO8601, use definitions in pyparsing_common
+date_expr = pyparsing_common.iso8601_date.setParseAction(pyparsing_common.convertToDate())
+date_expr.ignore(pythonStyleComment)
+
+date_expr.runTests("""\
+ 2000-01-01
+
+ # invalid month
+ 2000-13-01
+
+ # 1900 was not a leap year
+ 1900-02-29
+
+ # but 2000 was
+ 2000-02-29
+ """) \ No newline at end of file