Return date ISO8601 string formats for datetime, date, and time values, milliseconds for intervals
430675
def for_json(self):
        """"""
        value = super(DatetimeField, self).for_json()

        # Order of instance checks matters for proper inheritance checks
        if isinstance(value, pendulum.Interval):
            return value.in_seconds() * 1000
        if isinstance(value, datetime):
            return self.format_datetime(value)
        if isinstance(value, pendulum.Time):
            return str(value)
        if isinstance(value, pendulum.Date):
            return value.to_date_string()
694976
def as_iso8601(self):
        
        if self.__date is None or self.__time is None:
            return None

        return "20%s-%s-%sT%s:%s:%s0Z" % \
               (self.__date[4:], self.__date[2:4], self.__date[:2], self.__time[:2], self.__time[2:4], self.__time[4:])
1339784
def datetime(self):
        """"""
        if not self._datetime_calculated:
            self._datetime_calculated = True

            # if no datetime after 10 tokens, break to avoid parsing
            # very long lines
            split_tokens = self.split_tokens[:10]

            for offs in range(len(split_tokens)):
                dt = self._match_datetime_pattern(split_tokens[offs:offs + 4])
                if dt:
                    self._datetime = dt
                    self._datetime_nextpos = offs
                    if self._datetime_format.startswith("iso8601"):
                        self._datetime_nextpos += 1
                    else:
                        self._datetime_nextpos += 4

                    # separate datetime str and linestr
                    self._line_str = (' '.join(self.split_tokens
                                               [self._datetime_nextpos:]))

                    if self.level:
                        self._datetime_nextpos += 2

                    self._reformat_timestamp(self._datetime_format)
                    break

        return self._datetime
620615
def _parse_odata_timestamp(in_date):
    
    timestamp = int(in_date.replace('/Date(', '').replace(')/', ''))
    seconds = timestamp // 1000
    ms = timestamp % 1000
    return datetime.utcfromtimestamp(seconds) + timedelta(milliseconds=ms)
1172314
public static String formatISO8601Date(DateTime date) {
        try {
            return iso8601DateFormat.print(date);
        } catch (RuntimeException ex) {
            throw handleException(ex);
        }
    }
721182
def dateTimeToString(dateTime, convertToUTC=False):
    
    if dateTime.tzinfo and convertToUTC:
        dateTime = dateTime.astimezone(utc)

    datestr = "{}{}{}T{}{}{}".format(
        numToDigits(dateTime.year, 4),
        numToDigits(dateTime.month, 2),
        numToDigits(dateTime.day, 2),
        numToDigits(dateTime.hour, 2),
        numToDigits(dateTime.minute, 2),
        numToDigits(dateTime.second, 2),
    )
    if tzinfo_eq(dateTime.tzinfo, utc):
        datestr += "Z"
    return datestr
29512
def decimal_date(dateobs, timeobs=None):
    """"""

    year, month, day = dateobs.split('-')
    if timeobs is not None:
        hr, min, sec = timeobs.split(':')
    else:
        hr, min, sec = 0, 0, 0

    rdate = datetime.datetime(int(year), int(month), int(day), int(hr),
                              int(min), int(sec))
    dday = (float(rdate.strftime("%j")) + rdate.hour / 24.0 +
            rdate.minute / (60. * 24) + rdate.second / (3600 * 24.)) / 365.25
    ddate = int(year) + dday

    return ddate
1323982
def datetime_from_isoformat(value: str):
    
    if sys.version_info >= (3, 7):
        return datetime.fromisoformat(value)

    return datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%f')
881236
def encode_datetime(o):
    
    r = o.isoformat()
    if o.microsecond:
        r = r[:23] + r[26:]
    if r.endswith('+00:00'):
        r = r[:-6] + 'Z'
    return r
262857
def parse_datetime(datetimestring):
    '''
    
    '''
    try:
        datestring, timestring = re.split('T| ', datetimestring)
    except ValueError:
        raise isodate.ISO8601Error(
            "ISO 8601 time designator 'T' or ' '  missing. Unable to parse "
            "datetime string %r" % datetimestring
        )
    tmpdate = isodate.parse_date(datestring)
    tmptime = isodate.parse_time(timestring)
    return datetime.datetime.combine(tmpdate, tmptime)
461570
def iso_time_string(val, show_tzinfo=False):
    
    if not val:
        return ""
    if isinstance(val, six.string_types):
        dt = _parse_datetime_string(val)
    else:
        dt = val
    if not isinstance(dt, datetime.datetime):
        dt = datetime.datetime.fromordinal(dt.toordinal())
    has_tz = (dt.tzinfo is not None)
    if show_tzinfo and has_tz:
        # Need to remove the colon in the TZ portion
        ret = "".join(dt.isoformat().rsplit(":", 1))
    elif show_tzinfo and not has_tz:
        ret = "%s+0000" % dt.isoformat().split(".")[0]
    elif not show_tzinfo and has_tz:
        ret = dt.isoformat()[:-6]
    elif not show_tzinfo and not has_tz:
        ret = dt.isoformat().split(".")[0]
    return ret
1108714
def get_datetime_type(to_string):
    
    from datetime import datetime

    def datetime_type(string):
        """ Validates UTC datetime. Examples of accepted forms:
        2017-12-31T01:11:59Z,2017-12-31T01:11Z or 2017-12-31T01Z or 2017-12-31 """
        accepted_date_formats = ['%Y-%m-%dT%H:%M:%SZ', '%Y-%m-%dT%H:%MZ',
                                 '%Y-%m-%dT%HZ', '%Y-%m-%d']
        for form in accepted_date_formats:
            try:
                if to_string:
                    return datetime.strptime(string, form).strftime(form)

                return datetime.strptime(string, form)
            except ValueError:
                continue
        raise ValueError("Input '{}' not valid. Valid example: 2000-12-31T12:59:59Z".format(string))

    return datetime_type
709212
def formatDate( milliseconds, fmtString = nil, addDay = false )
      fmt = ""
      fmtString = "%m-%d-%Y" if fmtString.nil?
      if milliseconds
         milliseconds_s = milliseconds.to_s
         if milliseconds_s.length == 13
            t = Time.at( milliseconds_s[0,10].to_i,  milliseconds_s[10,3].to_i )
            t += (60 * 60 * 24) if addDay
            fmt = t.strftime(  fmtString )
         elsif milliseconds_s.length > 0
            t = Time.at( (milliseconds_s.to_i) / 1000 )
            t += (60 * 60 * 24) if addDay
            fmt = t.strftime(  fmtString )
         end
      end
      fmt
   end
15606
def parse_time(time_input):
    
    if isinstance(time_input, datetime.date):
        return time_input.isoformat()  # datetime.date only returns date, datetime.datetime also returns time

    if len(time_input) < 8:
        raise ValueError('Invalid time string {}.\n'
                         'Please specify time in formats YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS'.format(time_input))
    time = dateutil.parser.parse(time_input)
    if len(time_input) <= 10:
        return time.date().isoformat()
    return time.isoformat()
169431
def DateStringToDateObject(date_string):
  """"""
  # If this becomes a bottleneck date objects could be cached
  if re.match('^\d{8}$', date_string) == None:
    return None
  try:
    return datetime.date(int(date_string[0:4]), int(date_string[4:6]),
                         int(date_string[6:8]))
  except ValueError:
    return None
280367
def parseIBDatetime(s):
    
    if len(s) == 8:
        # YYYYmmdd
        y = int(s[0:4])
        m = int(s[4:6])
        d = int(s[6:8])
        dt = datetime.date(y, m, d)
    elif s.isdigit():
        dt = datetime.datetime.fromtimestamp(
            int(s), datetime.timezone.utc)
    else:
        dt = datetime.datetime.strptime(s, '%Y%m%d  %H:%M:%S')
    return dt
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