Skip to content

Instantly share code, notes, and snippets.

@sgammon
Last active December 22, 2015 16:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sgammon/6501156 to your computer and use it in GitHub Desktop.
Save sgammon/6501156 to your computer and use it in GitHub Desktop.
lambdas for dayssssssssssss
# -*- coding: utf-8 -*-
# stdlib
import time
import datetime
# `_TO_TIMESTAMP`: converts a python datetime into a integer timestamp
_TO_TIMESTAMP = lambda dt: int(time.mktime(dt.timetuple()))
# `_PROVIDER`: converts a provider name ("keen") to a sentinel for that provider (`KEEN`)
_PROVIDER = lambda name: getattr(Providers, name.upper()) # return ``KEEN`` for ``keen``
_PROVIDER_IMPL = lambda sentinel: globals()[''.join(sentinel.capitalize())] # return :py:class:`Keen` for ``KEEN``
# `_PRETTY_DATE`: output a string repr for a date that's easy on the eyes
_PRETTY_DATE = lambda _date: _date.strftime('%a %b %d, %Y')
# `_MAKE_TIMEZONE`: factory a :py:class:`tzinfo` descendant describing a timezone offset
_MAKE_TIMEZONE = lambda offset: type(_TZSHORT.get(offset, 'TZ'), (UserTimezone,), {'offset': offset})()
# `_EXTRACT_TIMEZONE`: extract a timezone offset from an ISO8601-formatted timestamp
_EXTRACT_TIMEZONE = lambda spec: _MAKE_TIMEZONE(spec) if not isinstance(spec, basestring) else ('Z' if 'Z' in spec else ('-%s' % spec.split('-')[-1] if '-' in spec.split('T')[-1] else '+%s' % spec.split('+')[-1]))
# `_GET_TIMEZONE`: generate a :py:class:`tzinfo` object describing a timezone with a UTC offset, given a timestamp offset
_GET_TIMEZONE = lambda offset: _MAKE_TIMEZONE(0) if offset in ('Z', '+00:00', '+00', '-00:00', '-00', '+0000') else _MAKE_TIMEZONE(((int(filter(lambda x: x in string.digits and x is not '0' and len(x) > 0, offset.split('0'))[0])) * (-1 if '-' in offset else 1)) + (.5 if '30' in offset else 0))
# `_GET_TIMEZONE_BY_NAME`: generate a :py:class:`tzinfo` object, like above, but from a named timezone instead of an offset string/integer
_GET_TIMEZONE_BY_NAME = lambda name: timezone(name)
# `_[TO/FROM]_KEEN_DATE`: converts to/from ISO8601 format and Python `date`
_TO_KEEN_DATE = lambda _date: ''.join((_date.strftime(_KEEN_DATE_FMT_ISO), 'Z' if not _date.tzinfo else ''))
_FROM_KEEN_DATE = lambda spec: (datetime.strptime('-'.join(spec.replace('Z', '').split('-')[0:3]).split('+')[0], _KEEN_DATE_FMT).replace(tzinfo=_GET_TIMEZONE(_EXTRACT_TIMEZONE(spec))) if (len(spec.split('-')) > 3 or '+' in spec or 'Z' in spec) else datetime.strptime(spec, _KEEN_DATE_FMT))
# `_[TO|FROM]_MIXPANEL_DATE`: converts to/from YYYY-MM-DD format and Python `date`
_TO_MIXPANEL_DATE = lambda _date: _date.strftime(_MIXPANEL_DATE_FMT)
_FROM_MIXPANEL_DATE = lambda spec: datetime.strptime(spec, _MIXPANEL_DATE_FMT)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment