def _testTexts(self, texts): c = pdc.Constants() p = pdt.Calendar(c) for name, list in texts.items(): print name for msg in list: dt = None (start, end, valid) = p.evalRanges(msg) if valid: prefix = "Range:" dt = (str(tuple_to_dt(start)), str(tuple_to_dt(end))) else: (t, valid) = p.parse(msg) if valid: dt = str(tuple_to_dt(t)) if valid == 1: prefix = "date :" elif valid == 2: prefix = "time :" elif valid == 3: prefix = "dt :" else: dt = "INVALID" prefix = "INVALID" print "\t", msg print "\t\t", prefix, dt print "\t\tEvent:", self.startTime(msg)
def reminder(self, params): targetdate = "" if params[1] == "remove": cursor = self.conn.cursor(MySQLdb.cursors.DictCursor) cursor.execute( 'select r.id FROM reminders r, todos t WHERE r.todo_id = t.id and t.pos = "%s" and t.jid="%s"' % (params[0], self.jid)) row = cursor.fetchone() if row is None: return "That reminder doesn't exist" cursor.execute("delete from reminders where id = '%s'" % row["id"]) return "removed reminder for %s" % params[0] c = pdc.Constants() p = pdt.Calendar(c) targetdate = p.parse(params[1]) year = targetdate[0][0] month = targetdate[0][1] day = targetdate[0][2] hour = targetdate[0][3] minute = targetdate[0][4] cursor = self.conn.cursor(MySQLdb.cursors.DictCursor) sql = "select id from todos where pos = '%s' and jid = '%s'" % ( params[0], self.jid) cursor.execute(sql) row = cursor.fetchone() if row is None: return "That item doesnt exist" sql = "insert into reminders (todo_id, rdate) values ('%s', '%d-%d-%d %d:%02d:00')" % ( row['id'], year, month, day, hour, minute) print 'reminder sql:' + sql cursor.execute(sql) return "reminder set for %d/%d/%d %d:%02d" % (month, day, year, hour, minute)
def datetimeFromString(s): c = pdc.Constants() p = pdt.Calendar(c) result, what = p.parse(s) dt = 0 if what in (1,2,3): dt = datetime.datetime( *result[:6] ) if what == 0: return "" return dt
def __get_pdt_calendar(): try: import parsedatetime.parsedatetime_consts as pdt except ImportError: import parsedatetime as pdt consts = pdt.Constants(usePyICU=False) consts.DOWParseStyle = -1 # "Monday" will be either today or the last Monday calendar = pdt.Calendar(consts) return calendar
def parse_date(date_string): '''Parse a time input using parsedatetime, allowing natural language''' c = pdc.Constants() p = pdt.Calendar(c) (result, parsed_as) = p.parse(date_string) # result of parse can take several forms # we need to return a datetime, as expected by boto if parsed_as is 0: raise opt.Usage("Couldn't parse date/time: " + date_string) elif parsed_as in (1, 2, 3): # result is a struct_time or a 9-tuple that can be handled by mktime return epoch_to_datetime(mktime(result)) else: raise opt.Usage("Unexpected result from parse_date")
def startTime(self, msg, constants=pdc.Constants()): parser = pdt.Calendar(constants) (start, end, valid) = parser.evalRanges(msg) if valid: return _dt(start) (start, valid) = parser.parse(msg) if valid == 1: # date return _dt(start) elif valid == 2: # time return _dt(start) elif valid == 3: # datetime return _dt(start) return None
def __init__(self, name='default', **kwargs): self.config = { 'journal': "journal.txt", 'encrypt': False, 'default_hour': 9, 'default_minute': 0, 'timeformat': "%Y-%m-%d %H:%M", 'tagsymbols': '@', 'highlight': True, 'linewrap': 80, } self.config.update(kwargs) # Set up date parser consts = pdt.Constants(usePyICU=False) consts.DOWParseStyle = -1 # "Monday" will be either today or the last Monday self.dateparse = pdt.Calendar(consts) self.key = None # used to decrypt and encrypt the journal self.search_tags = None # Store tags we're highlighting self.name = name self.open()
def __init__(self, **kwargs): self.config = { 'journal': "journal.txt", 'encrypt': False, 'password': "", 'default_hour': 9, 'default_minute': 0, 'timeformat': "%Y-%m-%d %H:%M", 'tagsymbols': '@', 'highlight': True, 'linewrap': 80, } self.config.update(kwargs) # Set up date parser consts = pdt.Constants(usePyICU=False) consts.DOWParseStyle = -1 # "Monday" will be either today or the last Monday self.dateparse = pdt.Calendar(consts) self.key = None # used to decrypt and encrypt the journal journal_txt = self.open() self.entries = self.parse(journal_txt) self.sort()
import yaml import jrnl.time from jrnl import Journal from jrnl import __version__ from jrnl import plugins from jrnl.cli import cli from jrnl.config import load_config from jrnl.os_compat import split_args try: import parsedatetime.parsedatetime_consts as pdt except ImportError: import parsedatetime as pdt 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)
http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import parsedatetime.parsedatetime as pdt import parsedatetime.parsedatetime_consts as pdc # create an instance of Constants class so we can specify the locale c = pdc.Constants("en") p = pdt.Calendar(c) # print out the values from Constants to show how the locale information # is being used/stored internally print c.uses24, c.usesMeridian # 24hr clock? AM/PM used? print c.usePyICU # was PyICU found/enabled? print c.meridian # list of the am and pm values print c.am # list of the lowercased and stripped am string print c.pm # list of the lowercased and stripped pm string print c.dateFormats # dictionary of available date format strings print c.timeFormats # dictionary of available time format strings print c.timeSep # list of time separator, e.g. the ':' in '12:45' print c.dateSep # list of date serarator, e.g. the '/' in '11/23/2006' print c.Months # list of full month names
def parse(s): """ Parse the string using parsedatetime and format it to the current timezone """ return TZ.localize( datetime(*tuple(pdt.Calendar(pdc.Constants()).parse(s)[0])[:7]))
reload(sys) sys.setdefaultencoding('utf-8') import os import datetime import csv from django.template.defaultfilters import slugify from parsedatetime import parsedatetime as pdt, parsedatetime_consts as pdc import time, datetime #### parsedatetime stuff # create an instance of Constants class so we can override some of the defaults c = pdc.Constants() # create an instance of the Calendar class and pass in our Constants # object instead of letting it create a default p = pdt.Calendar(c) # parse "tomorrow" and return the result #result = p.parse("tomorrow") # parseDate() is a helper function that bypasses all of the # natural language stuff and just tries to parse basic dates # but using the locale information #result = p.parseDate("4/4/80") #### globals trace = 0 teeth = 0 # whether to get latest extract from zope dbteeth = 1 # whether to update db
'rthc': 'chtr', 'poppy_nogood': 'chtr', 'octavious': 'joshc' }) server = 'irc.freenode.net' channel = '#rhnoise' # filename of weechat style irc log logfile = 'fish_scraps' # filename of shelved .delays shelffile = 'bookshelf' # parsedatetime constants pdc_const = pdc.Constants() pdc_cal = pdt.Calendar(pdc_const) class MarkBotFactory(protocol.ClientFactory): def __init__(self, channel, filename): self.channel = channel self.filename = filename def buildProtocol(self, addr): p = MarkBot() p.factory = self p.reshelve() return p def clientConnectionLost(self, connector, reason):
def setUp(self): self.ptc = ptc.Constants('en_AU', usePyICU=False) self.cal = pt.Calendar(self.ptc) self.yr, self.mth, self.dy, self.hr, self.mn, self.sec, self.wd, self.yd, self.isdst = time.localtime()
import datetime import json from django.http import HttpResponse from parsedatetime import parsedatetime, parsedatetime_consts def json_r(data_dict, cls=None): if not cls: cls = HttpResponse return cls(json.dumps(data_dict), mimetype='application/json') def smart_int(string, fallback=0): """Convert a string to int, with fallback for invalid strings or types.""" try: return int(float(string)) except (ValueError, TypeError): return fallback date_constants = parsedatetime_consts.Constants() date_parser = parsedatetime.Calendar(date_constants) def strtodatetime(string): return datetime.datetime(*date_parser.parse(string)[0][0:6])
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)