Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
parser.read(StringIO(data.INITIAL_GAME))
parser.flush()
assert parser.games[0].packets[0].ts == time(2, 59, 14, 608862)
# Test with an initial datetime
parser2 = LogParser()
parser2._current_date = datetime(2015, 1, 1)
parser2.read(StringIO(data.INITIAL_GAME))
parser2.flush()
assert parser2.games[0].packets[0].ts == datetime(2015, 1, 1, 2, 59, 14, 608862)
# Same test, with timezone
parser2 = LogParser()
parser2._current_date = parse_datetime("2015-01-01T02:58:00+0200")
parser2.read(StringIO(data.INITIAL_GAME))
parser2.flush()
ts = parser2.games[0].packets[0].ts
assert ts.year == 2015
assert ts.hour == 2
assert ts.second == 14
assert ts.tzinfo
assert ts.utcoffset() == timedelta(hours=2)
def on_restriction(rules, checkin, duration):
"""
Returns True if restrictions are consistent with the checkin
and duration given in argument. False otherwise
:param rules: list of rules (dict)
:param checkin: checkin time
:param duration: duration in hour. Float accepted
"""
checkin = parse_datetime(checkin)
duration = timedelta(hours=duration)
checkin_end = checkin + duration # datetime
month = checkin.date().month # month as number
isodow = checkin.isoweekday() # 1->7
year = checkin.year # 2015
day = checkin.strftime('%d') # 07
# analyze each rule and stop iteration on conflict
for rule in rules:
# first test season day/month
start_day, start_month = ('-' or rule['season_start']).split('-')
end_day, end_month = ('-' or rule['season_end']).split('-')
season_match = season_matching(
start_day,
If a `dict` is provided, does `datetime.datetime(**value)`.
If a `tuple` or a `list` is provided, does
`datetime.datetime(*value)`. Uses the timezone in the tuple or
list if provided.
:param value: something to convert
:type value: str | unicode | float | int | :class:`datetime.datetime` | dict | list | tuple
:return: the value after conversion
:rtype: :class:`datetime.datetime`
:raises: ValueError | TypeError
"""
if isinstance(value, basestring):
try:
return aniso8601.parse_datetime(value)
except Exception as e:
raise ValueError(
"Conversion to datetime.datetime failed. Could not "
"parse the given string as an ISO 8601 timestamp: "
"%s\n\n"
"%s" %
(
repr(value),
e.message,
)
)
try:
if isinstance(value, datetime.datetime):
return value
elif isinstance(value, dict):
def _parse_interval(value):
"""Do some nasty try/except voodoo to get some sort of datetime
object(s) out of the string.
"""
try:
return sorted(aniso8601.parse_interval(value))
except ValueError:
try:
return aniso8601.parse_datetime(value), None
except ValueError:
return aniso8601.parse_date(value), None
def _parse_timestamp(timestamp):
"""
Parse a given timestamp value, raising ValueError if None or Flasey
"""
if timestamp:
try:
return aniso8601.parse_datetime(timestamp)
except AttributeError:
# raised by aniso8601 if raw_timestamp is not valid string
# in ISO8601 format
try:
return datetime.utcfromtimestamp(timestamp)
except:
# relax the timestamp a bit in case it was sent in millis
return datetime.utcfromtimestamp(timestamp/1000)
raise ValueError('Invalid timestamp value! Cannot parse from either ISO8601 string or UTC timestamp.')
def __getattr__(self, attr):
# converts timestamp str to datetime.datetime object
if 'timestamp' in attr:
return aniso8601.parse_datetime(self.get(attr))
return self.get(attr)
def __getattr__(self, attr):
# converts timestamp str to datetime.datetime object
if 'timestamp' in attr:
return aniso8601.parse_datetime(self.get(attr))
return self.get(attr)
def on_restriction(slot, checkin, duration, paid=True, permit=False):
"""
Process rules for display to client. Returns rule(s) if restrictions are compatible with the checkin
and duration given in argument. False otherwise.
:param rules: list of rules (dict)
:param checkin: checkin time
:param duration: duration in hour. Float accepted
:param paid: set to False to not return any paid slots.
:param permit: return permit slots matching this name/number (str), 'all', or False for none
"""
checkin = parse_datetime(checkin)
duration = timedelta(hours=duration)
checkin_end = checkin + duration # datetime
month = checkin.date().month # month as number
isodow = checkin.isoweekday() # 1->7
year = checkin.year # 2015
day = int(checkin.strftime('%d')) # 07
slot['restrict_types'] = []
# add any applicable temporary restrictions into the main rules list
if slot.get('temporary_rule'):
slot["rules"].append(slot["temporary_rule"])
# analyze each rule: leave it alone if it is not currently restricted, return False if it is
for rule in slot["rules"]:
a.auth_type AS user_type,
COALESCE(s.rules, '[]'::jsonb) AS rules
FROM checkins c
LEFT JOIN slots s ON s.id = c.slot_id
JOIN users u ON c.user_id = u.id
JOIN cities ct ON (ST_intersects(s.geom, ct.geom)
OR ST_intersects(ST_transform(ST_SetSRID(ST_MakePoint(c.long, c.lat), 4326), 3857), ct.geom))
JOIN
(SELECT auth_type, user_id, max(id) AS id
FROM users_auth GROUP BY auth_type, user_id) a
ON c.user_id = a.user_id
WHERE ct.name = '{}'
{}
""".format(city,
((" AND (c.checkin_time AT TIME ZONE 'UTC') >= '{}'".format(aniso8601.parse_datetime(start).strftime("%Y-%m-%d %H:%M:%S"))) if start else "") +
((" AND (c.checkin_time AT TIME ZONE 'UTC') <= '{}'".format(aniso8601.parse_datetime(end).strftime("%Y-%m-%d %H:%M:%S"))) if end else "")
)).fetchall()
return [
{key: value for key, value in row.items()}
for row in res
]
def datetime_from_iso8601(datetime_str):
"""Turns an ISO8601 formatted date into a datetime object.
Example::
inputs.datetime_from_iso8601("2012-01-01T23:30:00+02:00")
:param datetime_str: The ISO8601-complying string to transform
:type datetime_str: str
:return: A datetime
"""
return aniso8601.parse_datetime(datetime_str)