Parses a given datetime string to milli seconds since 1970-01-01 00:00:00 UTC
using the default format "yyyy-MM-dd" or "yyyy-MM-dd HH:mm:ss" depends on the string length.
422982
private static long parseToTimeMillis(String dateStr, TimeZone tz) {
		String format;
		if (dateStr.length() <= 10) {
			format = DATE_FORMAT_STRING;
		} else {
			format = TIMESTAMP_FORMAT_STRING;
		}
		return parseToTimeMillis(dateStr, format, tz) + getMillis(dateStr);
	}
706251
public static String toStringWithSeconds( DateTime dateTime ) {
        String dtStr = dateTime.toString(withSecondsformatter);
        return dtStr;
    }
943282
def strptime(cls, date_string, format):
        ''
        import _strptime
        return _strptime._strptime_datetime(cls, date_string, format)
89729
def _parse_datetime_value(value):
    """"""
    if value.endswith('Z'):
        # Arrow doesn't support the "Z" literal to denote UTC time.
        # Strip the "Z" and add an explicit time zone instead.
        value = value[:-1] + '+00:00'

    return arrow.get(value, 'YYYY-MM-DDTHH:mm:ssZ').datetime
487975
def _strptime(self, time_str):
        """"""
        if time_str:
            # Parse UTC string into naive datetime, then add timezone
            dt = datetime.strptime(time_str, __timeformat__)
            return dt.replace(tzinfo=UTC())
        return None
1255577
def datetime2unix(T):
    
    T = atleast_1d(T)

    ut1_unix = empty(T.shape, dtype=float)
    for i, t in enumerate(T):
        if isinstance(t, (datetime, datetime64)):
            pass
        elif isinstance(t, str):
            try:
                ut1_unix[i] = float(t)  # it was ut1_unix in a string
                continue
            except ValueError:
                t = parse(t)  # datetime in a string
        elif isinstance(t, (float, int)):  # assuming ALL are ut1_unix already
            return T
        else:
            raise TypeError('I only accept datetime or parseable date string')

        # ut1 seconds since unix epoch, need [] for error case
        ut1_unix[i] = forceutc(t).timestamp()

    return ut1_unix
1293894
def valueFromString(self, value, context=None):
        
        if value in ('today', 'now'):
            return datetime.datetime.utcnow()
        elif dateutil_parser:
            return dateutil_parser.parse(value)
        else:
            time_struct = time.strptime(value, self.defaultFormat())
            return datetime.datetime(time_struct.tm_year,
                                     time_struct.tm_month,
                                     time_struct.tm_day,
                                     time_struct.tm_hour,
                                     time_struct.tm_minute,
                                     time_struct.tm_sec)
979129
public static DateTime parseTimeToday(String timeString) {
		timeString = StrUtil.format("{} {}", today(), timeString);
		return parse(timeString, DatePattern.NORM_DATETIME_FORMAT);
	}
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
1325347
private long parseDuration(String value) {
	        long periodMS = 0L;
	        if (value!=null) {
	            String[] parts = value.split(":");
	            for (int i = 0; i < parts.length; i++) {
	                switch (i) {
	                    case 0: // hours
	                        periodMS += (Integer.parseInt(parts[i])) * 3600000L;
	                        break;
	                    case 1: // minutes
	                        periodMS += (Integer.parseInt(parts[i])) * 60000L;
	                        break;
	                    case 2: // seconds
	                        periodMS += (Integer.parseInt(parts[i])) * 1000L;
	                        break;
	                    case 3: // ms
	                        periodMS += (Integer.parseInt(parts[i]));
	                        break;
	                    default:
	                        break;
	                }
	            }
	        }
	        return periodMS;
	    }
1306407
private Long trySeconds(String str) {

        for(String pattern : datePatterns) {

            SimpleDateFormat parser = new SimpleDateFormat(pattern, locale);

            try {
                long milliseconds = parser.parse(str).getTime();
                return milliseconds / 1000L;
            }
            catch(Exception e) {
                // Just ignore and try the next pattern in `datePatterns`.
            }
        }

        // Could not parse the string into a meaningful date, return null.
        return null;
    }
663642
private long parseDuration(String value) {
        long periodMS = 0L;
        if (Objects.nonNull(value)) {
            String[] parts = value.split(":");
            for (int i = 0; i < parts.length; i++) {
                switch (i) {
                    case 0: // hours
                        periodMS += (Integer.parseInt(parts[i])) * 3600000L;
                        break;
                    case 1: // minutes
                        periodMS += (Integer.parseInt(parts[i])) * 60000L;
                        break;
                    case 2: // seconds
                        periodMS += (Integer.parseInt(parts[i])) * 1000L;
                        break;
                    case 3: // ms
                        periodMS += (Integer.parseInt(parts[i]));
                        break;
                    default:
                        break;
                }
            }
        }
        return periodMS;
    }
1120050
def parse_now_field(s):
    """"""
    if not s.startswith('UTC:'):
        return None  # Invalid string
    s = s[4:]

    # isoformat can return strings both with and without microseconds - we
    # account for both
    try:
        dt = datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%f')
    except ValueError:
        dt = datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S')

    return dt
806723
def string2dt(self, s, lower_bound=None):
        """"""
        original_s = s

        result = {}
        dt = None

        # if s is completely empty, return start or end,
        # depending on what parameter is evaluated
        if s == '':
            return self.end if lower_bound else self.start

        # first try to match the defined regexes
        for idx in self.dtRegexes:
            regex = self.dtRegexes[idx]
            mo = regex.search(s)
            # if match was found, cut it out of original string and
            # store in result
            if mo:
                result[idx] = mo
                s = s[:mo.start(0)] + s[mo.end(0):]

        # handle constants
        if 'constant' in result:
            constant = result['constant'].group(0).strip()
            if constant == 'end':
                dt = self.end
            elif constant == 'start':
                dt = self.start
            elif constant == 'today':
                dt = datetime.now().replace(hour=0, minute=0, second=0,
                                            microsecond=0)
            elif constant == 'yesterday':
                dt = datetime.now().replace(hour=0, minute=0, second=0,
                                            microsecond=0) - timedelta(days=1)
            elif constant == 'now':
                dt = datetime.now()

        elif 'weekday' in result:
                weekday = result['weekday'].group(0).strip()
                # assume most-recently occured weekday in logfile
                most_recent_date = self.end.replace(hour=0, minute=0, second=0,
                                                    microsecond=0)
                offset = (most_recent_date.weekday() -
                          self.weekdays.index(weekday)) % 7
                dt = most_recent_date - timedelta(days=offset)

        # if anything remains unmatched, try parsing it with dateutil's parser
        if s.strip() != '':
            try:
                if dt:
                    dt = default_tzinfo(parser.parse(s, default=dt), tzutc)
                else:
                    # check if it's only time, then use the start dt as
                    # default, else just use the current year
                    if re.match('(?P<hour>\d{1,2}):(?P<minute>\d{2,2})'
                                '(?::(?P<second>\d{2,2})'
                                '(?:.(?P<microsecond>\d{3,3}))?)?'
                                '(?P<timezone>[0-9Z:\+\-]+)?$', s):
                        default = self.end if lower_bound else self.start
                    else:
                        default = datetime(self.end.year, 1, 1, 0, 0, 0)
                    default = default.replace(second=0, microsecond=0)

                    dt = parser.parse(s, default=default)

            except ValueError:
                raise ValueError("Error in DateTimeBoundaries: "
                                 "can't parse datetime from %s" % s)

        if not dt:
            dt = lower_bound or self.end

        # if no timezone specified, use the one from the logfile
        if dt.tzinfo is None:
            dt = dt.replace(tzinfo=self.start.tzinfo)

        # time is applied separately (not through the parser) so that string
        # containing only time don't use today as default date
        # (parser behavior)
        # if 'time' in result:
        #     dct = dict((k, int(v))
        #                for k,v in six.iteritems(result['time'].groupdict(0)))
        #     dct['microsecond'] *= 1000
        #     dt = dt.replace(**dct)

        # apply offset
        if 'offset' in result:

            # separate in operator, value, unit
            dct = result['offset'].groupdict()

            mult = 1
            if dct['unit'] in ['s', 'sec', 'secs']:
                dct['unit'] = 'seconds'
            elif dct['unit'] in ['m', 'min', 'mins']:
                dct['unit'] = 'minutes'
            elif dct['unit'] in ['h', 'hour', 'hours']:
                dct['unit'] = 'hours'
            elif dct['unit'] in ['d', 'day', 'days']:
                dct['unit'] = 'days'
            elif dct['unit'] in ['w', 'week', 'weeks']:
                dct['unit'] = 'days'
                mult = 7
            elif dct['unit'] in ['mo', 'month', 'months']:
                dct['unit'] = 'days'
                mult = 30.43
            elif dct['unit'] in ['y', 'year', 'years']:
                dct['unit'] = 'days'
                mult = 365.24

            if dct['operator'] == '-':
                mult *= -1

            dt = dt + eval('timedelta(%s=%i)' % (dct['unit'],
                                                 mult * int(dct['value'])))

        # if parsed datetime is out of bounds and no year specified,
        # try to adjust year
        year_present = re.search('\d{4,4}', original_s)

        if not year_present and 'constant' not in result:
            if (dt < self.start and
                    dt.replace(year=dt.year + 1) >= self.start and
                    dt.replace(year=dt.year + 1) <= self.end):
                dt = dt.replace(year=dt.year + 1)
            elif (dt > self.end and
                    dt.replace(year=dt.year - 1) >= self.start and
                    dt.replace(year=dt.year - 1) <= self.end):
                dt = dt.replace(year=dt.year - 1)

        return dt
1076078
def _parse_timestamp(timestamp):
        
        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.')
974671
def parse_isodate(datestr):
    
    m = isodate_rx.search(datestr)
    assert m, 'unrecognized date format: ' + datestr
    year, month, day = m.group('year', 'month', 'day')
    hour, minute, second, fraction = m.group('hour', 'minute', 'second', 'fraction')
    tz, tzhh, tzmm = m.group('tz', 'tzhh', 'tzmm')
    dt = datetime.datetime(int(year), int(month), int(day), int(hour))
    if fraction is None:
        fraction = 0
    else:
        fraction = float('0.' + fraction)
    if minute is None:
        dt = dt.replace(minute=int(60 * fraction))
    else:
        dt = dt.replace(minute=int(minute))
        if second is None:
            dt = dt.replace(second=int(60 * fraction))
        else:
            dt = dt.replace(second=int(second), microsecond=int(1000000 * fraction))
    if tz is not None:
        if tz[0] == 'Z':
            offset = 0
        else:
            offset = datetime.timedelta(minutes=int(tzmm or 0), hours=int(tzhh))
            if tz[0] == '-':
                offset = -offset
        dt = dt.replace(tzinfo=UTCOffset(offset))
    return dt
1103458
def dt_from_rfc8601(date_str):
    
    # Normalize string and adjust for milliseconds. Note that Python 2.6+ has
    # ".%f" format, but we're going for Python 2.5, so truncate the portion.
    date_str = date_str.rstrip('Z').split('.')[0]

    # Format string. (2010-04-13T14:02:48.000Z)
    fmt = "%Y-%m-%dT%H:%M:%S"
    # Python 2.6+: Could format and handle milliseconds.
    # if date_str.find('.') >= 0:
    #    fmt += ".%f"

    return datetime.strptime(date_str, fmt)