How to use the parsedatetime.parsedatetime_consts function in parsedatetime

To help you get started, we’ve selected a few parsedatetime examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github yang / flight-scraper / flightscraper / __init__.py View on Github external
from parsedatetime import parsedatetime as pdt, parsedatetime_consts as pdc

class html_compiler(pyjade.ext.html.HTMLCompiler):
  def visitCode(self, code):
    if not code.buffer and not code.block:
      exec code.val.lstrip() in self.global_context, self.local_context
    pyjade.ext.html.HTMLCompiler.visitCode(self, code)

def jade2html(tmpl, globals, locals):
  compiler = html_compiler(pyjade.Parser(tmpl).parse())
  env = dict(globals)
  env.update(locals)
  with pyjade.ext.html.local_context_manager(compiler, env):
    return compiler.compile()

date_parser = pdt.Calendar(pdc.Constants())
now = dt.datetime.now()

def month_of(date): return date + rd.relativedelta(day=1)
def fmt_time(time): return time.strftime('%a %Y-%m-%d %I:%M %p')
def fmt_date(date, short=False):
  return date.strftime('%m/%d/%Y') if not short else \
      '%s/%s/%s' % (date.month, date.day, date.year)
day_names = set.union(set([
  x.lower() for xs in calendar.day_name,calendar.day_abbr for x in xs]))
space = re.compile(r'\s+')
def parse_date(text):
  text = text.strip()
  if space.split(text, 1)[0].lower() in day_names:
    text = space.split(text, 1)[1]
  return dt.date(*date_parser.parse(text)[0][:3])
github spiffytech / spiffybot / modules / tell / tell.py View on Github external
cursor = dbConn.cursor()

    try:
        sendee = event.args.split()[0].lower()  # To whom should the message be delivered
    except:
        event.reply("You didn't send me a valid argument!")
        return
    if sendee == "me" or sendee == "myself":
        sendee = event.sender
    message = " ".join(event.args.split()[1:])
    if len(message.split(" in ")) > 1:
        message = " ".join(message.split(" in ")[:-1])

    # Parse the time to deliver the message (if any)
    deliver = event.args.split(" in ")[-1]
    p = pdt.Calendar(pdc.Constants())  # Use parsedatetime module to easily handle human date formatting
    deliver = p.parse(deliver)
    if deliver[1] == 0:  # Tried to parse an invalid time (i.e., we can't parse "stuff")
        deliver = None
    else:
        deliver = deliver[0]
        deliver = "%d-%d-%d %d:%d:%d" % (deliver[0], deliver[1], deliver[2], deliver[3], deliver[4], deliver[5])  # Format the deliver into a string for toEpoch()
        deliver = epochTools.toEpoch(deliver, format="%Y-%m-%d %H:%M:%S")  # deliverstamp for DB storage

    cursor.execute("insert into tell (sender, sendee, channel, message, deliver, sent) values (?, ?, ?, ?, ?, ?)", (event.sender, sendee, event.channel, message, deliver, time.time()))
    event.reply("Will do!")
    dbConn.commit()
github owenmorris / chandler / chandler / parcels / osaf / views / detail / detail.py View on Github external
oldValue = getattr(item, attributeName, None)
            # Here, the ICUError covers ICU being unable to handle
            # the input value. ValueErrors can occur when I've seen ICU
            # claims to parse bogus  values like "06/05/0506/05/05" 
            #successfully, which causes fromtimestamp() to throw.)
            try:
                dateTimeValue = pim.shortDateFormat.parse(item.itsView, 
                                                           newValueString,
                                                           oldValue)
            except (ICUError, ValueError):
                dateTimeValue = None

            if dateTimeValue is None:
                try:
                    # use parsedatetime to calculate the date
                    cal = parsedatetime.Calendar(ptc.Constants(
                                                        str(getLocale())))
                    (dateVar, invalidFlag) = cal.parse(newValueString)
                    #invalidFlag = 0 implies no date/time
                    #invalidFlag = 2 implies only time, no date
                    if invalidFlag not in (0, 2):
                        dateTimeValue = datetime(*dateVar[:3])
                except (ICUError, ValueError):
                    pass

            if dateTimeValue is None:
                self._changeTextQuietly(self.control, "%s ?" % newValueString)
                return


            # If this results in a new value, put it back.
            value = datetime.combine(dateTimeValue.date(), oldValue.timetz())
github owenmorris / chandler / chandler / parcels / osaf / pim / calendar / Calendar.py View on Github external
def parseText(view, text, locale=None):
    """
    Parses the given text and returns the start date/time and the end date/time and
    a countFlag  and a typeFlag.

    countFlag indicates the number of date/times present in the text. It is an enum.
    0 indicates no date/time, 1 indicates only one date/time, 2 indicates more than one date/time.

    typeFlag indicates the type of date/time information present. It is an ennum too.
    0 indicates no date/time, 1 indicates only date, 2 indicates only time
    and 3 indicates both date and time
    """
    loc = str(locale is not None and locale or getLocale())

    cal = parsedatetime.Calendar(ptc.Constants(loc))
    countFlag = 0   #counts the number of date/times in the text

    # The tokenizer will split large
    # bodies of text in to locale aware sentences.
    st = tokenizer.SentenceTokenizer(text, loc)
    for line in st.nextToken():
        if  countFlag > 1:
            #More than one date time exists.
            break
        else:
            (dt1, dt2, typeFlag) = cal.evalRanges(line)
            if typeFlag != 0:
                countFlag += 1
                # Date/time range exists
                (yr1, mth1, dy1, hr1, mn1, sec1, wd1, yd1, isdst1) = dt1
                (yr2, mth2, dy2, hr2, mn2, sec2, wd2, yd2, isdst2) = dt2
github owenmorris / chandler / chandler / parcels / osaf / framework / attributeEditors / AttributeEditors.py View on Github external
def parseDate(cls, view, target):
        """Parses Natural Language date strings using parsedatetime library."""
        target = target.lower()
        for matchKey in cls.textMatches:
            #natural language string for date found
            if ((cls.textMatches[matchKey]).lower()).startswith(target):
                cal = parsedatetime.Calendar()
                (dateVar, invalidFlag) = cal.parse(matchKey)
                #invalidFlag = 0 implies no date/time
                #invalidFlag = 2 implies only time, no date
                if invalidFlag != 0 and invalidFlag != 2:
                    dateStr = pim.shortDateFormat.format(view, datetime(*dateVar[:3]))
                    matchKey = cls.textMatches[matchKey]+ " : %s" % dateStr
                    yield matchKey
            else:
                cal = parsedatetime.Calendar(ptc.Constants(str(getLocale())))
                (dateVar, invalidFlag) = cal.parse(target)
                #invalidFlag = 0 implies no date/time
                #invalidFlag = 2 implies only time, no date
                if invalidFlag != 0 and invalidFlag != 2:
                    # temporary fix: parsedatetime sometimes returns day == 0
                    if not filter(lambda x: not x, dateVar[:3]):
                        match = pim.shortDateFormat.format(view, datetime(*dateVar[:3]))
                        if unicode(match).lower() != target:
                            yield match
                        break
github owenmorris / chandler / chandler / parcels / osaf / pim / calendar / Calendar.py View on Github external
0 indicates no date/time, 1 indicates only one date/time, 2 indicates more than one date/time.

    typeFlag indicates the type of date/time information present. It is an ennum too.
    0 indicates no date/time, 1 indicates only date, 2 indicates only time
    and 3 indicates both date and time
    """

    import parsedatetime.parsedatetime as parsedatetime
    import parsedatetime.parsedatetime_consts as ptc
    from i18n import getLocale
    import time
    import string

    loc = str(locale is not None and locale or getLocale())

    cal = parsedatetime.Calendar(ptc.Constants(loc))
    countFlag = 0   #counts the number of date/times in the text

    # The tokenizer will split large
    # bodies of text in to locale aware sentences.
    st = tokenizer.SentenceTokenizer(text, loc)
    for line in st.nextToken():
        if  countFlag > 1:
            #More than one date time exists.
            break
        else:
            (dt1, dt2, typeFlag) = cal.evalRanges(line)
            if typeFlag != 0:
                countFlag += 1
                # Date/time range exists
                (yr1, mth1, dy1, hr1, mn1, sec1, wd1, yd1, isdst1) = dt1
                (yr2, mth2, dy2, hr2, mn2, sec2, wd2, yd2, isdst2) = dt2
github armet / python-armet / src / armet / resources / attributes.py View on Github external
def _try(value):
        try:
            # Attempt to use the dateutil library to parse.
            from dateutil.parser import parse
            return parse(value, fuzzy=False)

        except ValueError:
            # Not a strictly formatted date; return nothing.
            pass

        try:
            import parsedatetime.parsedatetime as pdt
            import parsedatetime.parsedatetime_consts as pdc
            c = pdc.Constants()
            c.BirthdayEpoch = 80
            p = pdt.Calendar(c)
            result = p.parse(value)
            if result[1] != 0:
                return datetime.fromtimestamp(mktime(result[0]))

        except NameError:
            # No magic date/time support
            pass
github jrnl-org / jrnl / features / steps / core.py View on Github external
from collections import defaultdict

try:
    import parsedatetime.parsedatetime_consts as pdt
except ImportError:
    import parsedatetime as pdt
import time
import os
import json
import yaml
import keyring
import tzlocal
import shlex
import sys

consts = pdt.Constants(usePyICU=False)
consts.DOWParseStyle = -1  # Prefers past weekdays
CALENDAR = pdt.Calendar(consts)


class TestKeyring(keyring.backend.KeyringBackend):
    """A test keyring that just stores its values in a hash"""

    priority = 1
    keys = defaultdict(dict)

    def set_password(self, servicename, username, password):
        self.keys[servicename][username] = password

    def get_password(self, servicename, username):
        return self.keys[servicename].get(username)