Convert dates/datetimes to preferred string format if specified
        i.e. '%Y-%m-%d', 'epoch', 'iso'
771550
def convert_date_columns(df, date_format='epoch'):
    

    if date_format not in ['epoch', 'iso']:
        if '%' in date_format:
            try:
                datetime.datetime.now().strftime(date_format)
            except:
                raise DateConversionError('Error serializing dates in DataFrame using format {}.'.format(date_format))
            finally:
                for column, data_type in df.dtypes.to_dict().items():
                    if 'date' in str(data_type):
                        df[column] = df[column].dt.strftime(date_format)
        else:
            raise DateConversionError('Error serializing dates in DataFrame using format {}.'.format(date_format))

    return df
1061780
def convert_time_string(date_str):
    
    dt, _, _ = date_str.partition(".")
    dt = datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S")
    return dt
10028
def _encode_datetime(obj):
    """"""

    if isinstance(obj, datetime.datetime):
        obj = {'__datetime__': True, 'as_str': obj.strftime("%Y%m%dT%H:%M:%S.%f").encode()}
    return obj
1184646
def date_convert(string, match, ymd=None, mdy=None, dmy=None,
        d_m_y=None, hms=None, am=None, tz=None, mm=None, dd=None):
    '''
    '''
    groups = match.groups()
    time_only = False
    if mm and dd:
        y=datetime.today().year
        m=groups[mm]
        d=groups[dd]
    elif ymd is not None:
        y, m, d = re.split(r'[-/\s]', groups[ymd])
    elif mdy is not None:
        m, d, y = re.split(r'[-/\s]', groups[mdy])
    elif dmy is not None:
        d, m, y = re.split(r'[-/\s]', groups[dmy])
    elif d_m_y is not None:
        d, m, y = d_m_y
        d = groups[d]
        m = groups[m]
        y = groups[y]
    else:
        time_only = True

    H = M = S = u = 0
    if hms is not None and groups[hms]:
        t = groups[hms].split(':')
        if len(t) == 2:
            H, M = t
        else:
            H, M, S = t
            if '.' in S:
                S, u = S.split('.')
                u = int(float('.' + u) * 1000000)
            S = int(S)
        H = int(H)
        M = int(M)

    if am is not None:
        am = groups[am]
        if am:
            am = am.strip()
        if am == 'AM' and H == 12:
            # correction for "12" hour functioning as "0" hour: 12:15 AM = 00:15 by 24 hr clock
            H -= 12
        elif am == 'PM' and H == 12:
            # no correction needed: 12PM is midday, 12:00 by 24 hour clock
            pass
        elif am == 'PM':
            H += 12

    if tz is not None:
        tz = groups[tz]
    if tz == 'Z':
        tz = FixedTzOffset(0, 'UTC')
    elif tz:
        tz = tz.strip()
        if tz.isupper():
            # TODO use the awesome python TZ module?
            pass
        else:
            sign = tz[0]
            if ':' in tz:
                tzh, tzm = tz[1:].split(':')
            elif len(tz) == 4:  # 'snnn'
                tzh, tzm = tz[1], tz[2:4]
            else:
                tzh, tzm = tz[1:3], tz[3:5]
            offset = int(tzm) + int(tzh) * 60
            if sign == '-':
                offset = -offset
            tz = FixedTzOffset(offset, tz)

    if time_only:
        d = time(H, M, S, u, tzinfo=tz)
    else:
        y = int(y)
        if m.isdigit():
            m = int(m)
        else:
            m = MONTHS_MAP[m]
        d = int(d)
        d = datetime(y, m, d, H, M, S, u, tzinfo=tz)

    return d
962113
def to_isostring(dt):
    
    if dt.tzinfo is not None and dt.tzinfo.utcoffset(dt) > timedelta(0):
        logging.warn('Warning: aware datetimes are interpreted as if they were naive')

    # -3 to change microseconds to milliseconds
    return dt.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'
1088676
def CopyToDateTimeString(self):
    
    if (self._timestamp is None or self._timestamp < 0 or
        self._timestamp > self._UINT64_MAX):
      return None

    timestamp, remainder = divmod(self._timestamp, self._100NS_PER_SECOND)
    number_of_days, hours, minutes, seconds = self._GetTimeValues(timestamp)

    year, month, day_of_month = self._GetDateValuesWithEpoch(
        number_of_days, self._EPOCH)

    return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}.{6:07d}'.format(
        year, month, day_of_month, hours, minutes, seconds, remainder)
644350
def CopyToDateTimeString(self):
    
    if self._timestamp is None:
      return None

    number_of_days, hours, minutes, seconds = self._GetTimeValues(
        self._timestamp)

    year, month, day_of_month = self._GetDateValuesWithEpoch(
        number_of_days, self._EPOCH)

    return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}'.format(
        year, month, day_of_month, hours, minutes, seconds)
700394
def str_to_date(date: str) -> datetime.datetime:
    
    date = date.split('.')
    date.reverse()
    y, m, d = date
    return datetime.datetime(int(y), int(m), int(d))
983585
def date_from_string(string, format_string=None):
    """"""

    if isinstance(format_string, str):
        return datetime.datetime.strptime(string, format_string).date()

    elif format_string is None:
        format_string = [
            "%Y-%m-%d",
            "%m-%d-%Y",
            "%m/%d/%Y",
            "%d/%m/%Y",
        ]

    for format in format_string:
        try:
            return datetime.datetime.strptime(string, format).date()
        except ValueError:
            continue

    raise ValueError("Could not produce date from string: {}".format(string))
1167032
def _encode_datetime(name, value, dummy0, dummy1):
    """"""
    if value.utcoffset() is not None:
        value = value - value.utcoffset()
    millis = int(calendar.timegm(value.timetuple()) * 1000 +
                 value.microsecond / 1000)
    return b"\x09" + name + _PACK_LONG(millis)
287860
def _iso8601_to_localized_time(date_string):
    
    parsed_date = datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S.%fZ')
    localized_time = pytz.utc.localize(parsed_date)
    return localized_time
1132951
def epoch(ctx, datetime):
    
    return conversions.to_decimal(str(conversions.to_datetime(datetime, ctx).timestamp()), ctx)
119352
def to_datetime(date_or_datetime):
    
    if isinstance(date_or_datetime, date) and \
            not isinstance(date_or_datetime, datetime):
        d = date_or_datetime
        return datetime.strptime(
            '%04d-%02d-%02d' % (d.year, d.month, d.day), '%Y-%m-%d')
    return date_or_datetime
27086
def from_iso_date_string(self, date_str: str) -> datetime:
        
        assert isinstance(date_str, str)

        self.value = datetime.strptime(date_str, ISO_DATE_FORMAT)
        return self.value
34415
def _dateversion(self):
        # type: () -> int
        """"""
        import re
        if self._head:
            ma = re.search(r'(?<=\()(.*)(?=\))', self._head)
            if ma:
                s = re.split(r'[, ]+', ma.group(0))
                if len(s) >= 3:
                    # month
                    month_names = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                                   'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')
                    if s[0] in month_names:
                        m = month_names.index(s[0]) + 1
                        # date
                        if s[1].isdigit():
                            d = int(s[1])
                            if 1 <= d <= 31:
                                # year
                                if s[2].isdigit():
                                    y = int(s[2])
                                    if y >= 1:
                                        # Return an integer as "yyyymmdd".
                                        return y * 10000 + m * 100 + d
            raise ValueError('failed to parse "{0}"'.format(self._head))
        raise ValueError('no first line')
861283
def _str_to_datetime(datestr):
    
    # try known string
    try:
        return DATE_STRINGS[str(datestr).lower()]()
    except KeyError:  # any other string
        pass

    # use maya
    try:
        import maya
        return maya.when(datestr).datetime()
    except ImportError:
        pass

    # use dateutil.parse
    with warnings.catch_warnings():
        # don't allow lazy passing of time-zones
        warnings.simplefilter("error", RuntimeWarning)
        try:
            return dateparser.parse(datestr)
        except RuntimeWarning:
            raise ValueError("Cannot parse date string with timezone "
                             "without maya, please install maya")
        except (ValueError, TypeError) as exc:  # improve error reporting
            exc.args = ("Cannot parse date string {0!r}: {1}".format(
                datestr, exc.args[0]),)
            raise
331169
def provide_with_datetime_format(data, using)
      return unless defined?(Daru)
      return unless data.is_a?(Daru::DataFrame) || data.is_a?(Daru::Vector)
      return unless data.index.first.is_a?(DateTime)
      return if using[0..1] != '1:'
      @options = Hamster::Hash.new(
        xdata: 'time',
        timefmt: '%Y-%m-%dT%H:%M:%S',
        format_x: '%d\n%b\n%Y'
      ).merge(@options)
    end