druidG.g:559:1: isoTime returns [String date] : (d= DATE_YEAR_ONLY |d= DATE_YEAR_MONTH_ONLY |d= DATE |d= DATE_HOUR |d= DATE_HOUR_MIN |d= DATE_HOUR_MIN_SEC |d= DATE_HOUR_MIN_SEC_SUB |d= DATE_HOUR_MIN_SEC_SUB_TZ |d= DATE_HOUR_MIN_SEC_SUB_UTC_TZ );
424392
public final druidGParser.isoTime_return isoTime() throws RecognitionException {
		druidGParser.isoTime_return retval = new druidGParser.isoTime_return();
		retval.start = input.LT(1);

		Token d=null;

		try {
			// druidG.g:560:2: (d= DATE_YEAR_ONLY |d= DATE_YEAR_MONTH_ONLY |d= DATE |d= DATE_HOUR |d= DATE_HOUR_MIN |d= DATE_HOUR_MIN_SEC |d= DATE_HOUR_MIN_SEC_SUB |d= DATE_HOUR_MIN_SEC_SUB_TZ |d= DATE_HOUR_MIN_SEC_SUB_UTC_TZ )
			int alt221=9;
			switch ( input.LA(1) ) {
			case DATE_YEAR_ONLY:
				{
				alt221=1;
				}
				break;
			case DATE_YEAR_MONTH_ONLY:
				{
				alt221=2;
				}
				break;
			case DATE:
				{
				alt221=3;
				}
				break;
			case DATE_HOUR:
				{
				alt221=4;
				}
				break;
			case DATE_HOUR_MIN:
				{
				alt221=5;
				}
				break;
			case DATE_HOUR_MIN_SEC:
				{
				alt221=6;
				}
				break;
			case DATE_HOUR_MIN_SEC_SUB:
				{
				alt221=7;
				}
				break;
			case DATE_HOUR_MIN_SEC_SUB_TZ:
				{
				alt221=8;
				}
				break;
			case DATE_HOUR_MIN_SEC_SUB_UTC_TZ:
				{
				alt221=9;
				}
				break;
			default:
				NoViableAltException nvae =
					new NoViableAltException("", 221, 0, input);
				throw nvae;
			}
			switch (alt221) {
				case 1 :
					// druidG.g:560:3: d= DATE_YEAR_ONLY
					{
					d=(Token)match(input,DATE_YEAR_ONLY,FOLLOW_DATE_YEAR_ONLY_in_isoTime3625); 
					retval.date = (d!=null?d.getText():null);
					}
					break;
				case 2 :
					// druidG.g:561:3: d= DATE_YEAR_MONTH_ONLY
					{
					d=(Token)match(input,DATE_YEAR_MONTH_ONLY,FOLLOW_DATE_YEAR_MONTH_ONLY_in_isoTime3633); 
					retval.date = (d!=null?d.getText():null);
					}
					break;
				case 3 :
					// druidG.g:562:3: d= DATE
					{
					d=(Token)match(input,DATE,FOLLOW_DATE_in_isoTime3641); 
					retval.date = (d!=null?d.getText():null);
					}
					break;
				case 4 :
					// druidG.g:563:3: d= DATE_HOUR
					{
					d=(Token)match(input,DATE_HOUR,FOLLOW_DATE_HOUR_in_isoTime3649); 
					retval.date = (d!=null?d.getText():null);
					}
					break;
				case 5 :
					// druidG.g:564:3: d= DATE_HOUR_MIN
					{
					d=(Token)match(input,DATE_HOUR_MIN,FOLLOW_DATE_HOUR_MIN_in_isoTime3657); 
					retval.date = (d!=null?d.getText():null);
					}
					break;
				case 6 :
					// druidG.g:565:3: d= DATE_HOUR_MIN_SEC
					{
					d=(Token)match(input,DATE_HOUR_MIN_SEC,FOLLOW_DATE_HOUR_MIN_SEC_in_isoTime3665); 
					retval.date = (d!=null?d.getText():null);
					}
					break;
				case 7 :
					// druidG.g:566:3: d= DATE_HOUR_MIN_SEC_SUB
					{
					d=(Token)match(input,DATE_HOUR_MIN_SEC_SUB,FOLLOW_DATE_HOUR_MIN_SEC_SUB_in_isoTime3673); 
					retval.date = (d!=null?d.getText():null);
					}
					break;
				case 8 :
					// druidG.g:567:3: d= DATE_HOUR_MIN_SEC_SUB_TZ
					{
					d=(Token)match(input,DATE_HOUR_MIN_SEC_SUB_TZ,FOLLOW_DATE_HOUR_MIN_SEC_SUB_TZ_in_isoTime3681); 
					retval.date = (d!=null?d.getText():null);
					}
					break;
				case 9 :
					// druidG.g:568:3: d= DATE_HOUR_MIN_SEC_SUB_UTC_TZ
					{
					d=(Token)match(input,DATE_HOUR_MIN_SEC_SUB_UTC_TZ,FOLLOW_DATE_HOUR_MIN_SEC_SUB_UTC_TZ_in_isoTime3689); 
					retval.date = (d!=null?d.getText():null);
					}
					break;

			}
			retval.stop = input.LT(-1);

		}
		catch (RecognitionException re) {
			reportError(re);
			recover(input,re);
		}
		finally {
			// do for sure before leaving
		}
		return retval;
	}
1155982
def parse_iso8601_datetime(string):
    

    # Match ISO 8601?
    match = _RE_ISO8601_DATETIME.search(string)
    if not match:
        raise ValueError('Expected ISO 8601 date/time')

    # Extract ISO 8601 components
    year = int(match.group('year'))
    month = int(match.group('month'))
    day = int(match.group('day'))
    hour = int(match.group('hour')) if match.group('hour') else 0
    minute = int(match.group('min')) if match.group('min') else 0
    sec = int(match.group('sec')) if match.group('sec') else 0
    microsec = int(float('.' + match.group('fracsec')) * 1000000) if match.group('fracsec') else 0
    offhour = int(match.group('offsign') + match.group('offhour')) if match.group('offhour') else 0
    offmin = int(match.group('offsign') + match.group('offmin')) if match.group('offmin') else 0

    return (datetime(year, month, day, hour, minute, sec, microsec, TZUTC) -
            timedelta(hours=offhour, minutes=offmin))
311688
def format_date(date):
        
        # Handle time typing
        try:
            date = date.isoformat()
        except AttributeError:  # Not a datetime object
            date = str(date)

        date = parser.parse(date).strftime('%Y-%m-%d')
        return date
165985
def _datetime_to_iso8601(self, query_dict):
        """"""
        return {
            k: v if not isinstance(v, datetime.datetime) else v.isoformat()
            for k, v in list(query_dict.items())
        }
1039045
def strp_isoformat(strg):
    
    if isinstance(strg, datetime):
        return strg
    if len(strg) < 19 or len(strg) > 26:
        if len(strg) > 30:
            strg = strg[:30] + '...'
        raise ValueError("Invalid ISO formatted time string '%s'"%strg)
    if strg.find(".") == -1:
        strg += '.000000'
    if sys.version[0:3] >= '2.6':
        return datetime.strptime(strg, "%Y-%m-%dT%H:%M:%S.%f")
    else:
        dat, mis = strg.split(".")
        dat = datetime.strptime(dat, "%Y-%m-%dT%H:%M:%S")
        mis = int(float('.' + mis)*1000000)
        return dat.replace(microsecond=mis)
442471
def iso8601_date(d):
    
    if d == values.unset:
        return d
    elif isinstance(d, datetime.datetime):
        return str(d.date())
    elif isinstance(d, datetime.date):
        return str(d)
    elif isinstance(d, str):
        return d
1035132
def _parse_date_iso8601(dateString):
    ''''''
    m = None
    for _iso8601_match in _iso8601_matches:
        m = _iso8601_match(dateString)
        if m:
            break
    if not m:
        return
    if m.span() == (0, 0):
        return
    params = m.groupdict()
    ordinal = params.get('ordinal', 0)
    if ordinal:
        ordinal = int(ordinal)
    else:
        ordinal = 0
    year = params.get('year', '--')
    if not year or year == '--':
        year = time.gmtime()[0]
    elif len(year) == 2:
        # ISO 8601 assumes current century, i.e. 93 -> 2093, NOT 1993
        year = 100 * int(time.gmtime()[0] / 100) + int(year)
    else:
        year = int(year)
    month = params.get('month', '-')
    if not month or month == '-':
        # ordinals are NOT normalized by mktime, we simulate them
        # by setting month=1, day=ordinal
        if ordinal:
            month = 1
        else:
            month = time.gmtime()[1]
    month = int(month)
    day = params.get('day', 0)
    if not day:
        # see above
        if ordinal:
            day = ordinal
        elif params.get('century', 0) or \
                 params.get('year', 0) or params.get('month', 0):
            day = 1
        else:
            day = time.gmtime()[2]
    else:
        day = int(day)
    # special case of the century - is the first year of the 21st century
    # 2000 or 2001 ? The debate goes on...
    if 'century' in params:
        year = (int(params['century']) - 1) * 100 + 1
    # in ISO 8601 most fields are optional
    for field in ['hour', 'minute', 'second', 'tzhour', 'tzmin']:
        if not params.get(field, None):
            params[field] = 0
    hour = int(params.get('hour', 0))
    minute = int(params.get('minute', 0))
    second = int(float(params.get('second', 0)))
    # weekday is normalized by mktime(), we can ignore it
    weekday = 0
    daylight_savings_flag = -1
    tm = [year, month, day, hour, minute, second, weekday,
          ordinal, daylight_savings_flag]
    # ISO 8601 time zone adjustments
    tz = params.get('tz')
    if tz and tz != 'Z':
        if tz[0] == '-':
            tm[3] += int(params.get('tzhour', 0))
            tm[4] += int(params.get('tzmin', 0))
        elif tz[0] == '+':
            tm[3] -= int(params.get('tzhour', 0))
            tm[4] -= int(params.get('tzmin', 0))
        else:
            return None
    # Python's time.mktime() is a wrapper around the ANSI C mktime(3c)
    # which is guaranteed to normalize d/m/y/h/m/s.
    # Many implementations have bugs, but we'll pretend they don't.
    return time.localtime(time.mktime(tuple(tm)))
873467
def um_date_to_date(d):
    

    return datetime.datetime(year=d[0], month=d[1], day=d[2],
                             hour=d[3], minute=d[4], second=d[5])
521178
def date(self):
        ''' 
        '''
        utcnow = datetime.utcnow()
        return (utcnow + timedelta(hours=self.time_zone)).date()
1117725
def asDateTime(self):
        
        text = str(self)
        if text.endswith('Z'):
            tzinfo = TimeMixIn.UTC
            text = text[:-1]

        elif '-' in text or '+' in text:
            if '+' in text:
                text, plusminus, tz = string.partition(text, '+')
            else:
                text, plusminus, tz = string.partition(text, '-')

            if self._shortTZ and len(tz) == 2:
                tz += '00'

            if len(tz) != 4:
                raise error.PyAsn1Error('malformed time zone offset %s' % tz)

            try:
                minutes = int(tz[:2]) * 60 + int(tz[2:])
                if plusminus == '-':
                    minutes *= -1

            except ValueError:
                raise error.PyAsn1Error('unknown time specification %s' % self)

            tzinfo = TimeMixIn.FixedOffset(minutes, '?')

        else:
            tzinfo = None

        if '.' in text or ',' in text:
            if '.' in text:
                text, _, ms = string.partition(text, '.')
            else:
                text, _, ms = string.partition(text, ',')

            try:
                ms = int(ms) * 1000

            except ValueError:
                raise error.PyAsn1Error('bad sub-second time specification %s' % self)

        else:
            ms = 0

        if self._optionalMinutes and len(text) - self._yearsDigits == 6:
            text += '0000'
        elif len(text) - self._yearsDigits == 8:
            text += '00'

        try:
            dt = dateandtime.strptime(text, self._yearsDigits == 4 and '%Y%m%d%H%M%S' or '%y%m%d%H%M%S')

        except ValueError:
            raise error.PyAsn1Error('malformed datetime format %s' % self)

        return dt.replace(microsecond=ms, tzinfo=tzinfo)
1080390
def to_iso_date(self, dt):
        
        if dt is None:
            return ""
        if isinstance(dt, DateTime):
            return dt.ISO8601()
        if isinstance(dt, datetime):
            return dt.isoformat()
        raise TypeError("{} is neiter an instance of DateTime nor datetime"
                        .format(repr(dt)))
1235259
def isoformat(self):
        
        text = [self.strftime('%Y-%m-%dT%H:%M:%S'), ]
        if self.tzinfo:
            text.append(self.tzinfo.as_timezone())
        else:
            text.append('+00:00')
        return ''.join(text)
983708
def timedelta_isoformat(td: datetime.timedelta) -> str:
    
    minutes, seconds = divmod(td.seconds, 60)
    hours, minutes = divmod(minutes, 60)
    return f'P{td.days}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S'
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()
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'
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:])
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