Return datetime object from a timex constraint start/end entry.

    Example string format to convert: 2018-01-01T00:00
18879
def _get_time_stamp(entry):
    
    if not entry or entry == 'Undef':
        return None
    try:
        dt = datetime.datetime.strptime(entry, '%Y-%m-%dT%H:%M')
    except Exception as e:
        logger.debug('Could not parse %s format' % entry)
        return None
    return dt
162121
def to_date(value, default=None):
    
    if isinstance(value, DateTime):
        return value
    if not value:
        if default is None:
            return None
        return to_date(default)
    try:
        if isinstance(value, str) and '.' in value:
            # https://docs.plone.org/develop/plone/misc/datetime.html#datetime-problems-and-pitfalls
            return DateTime(value, datefmt='international')
        return DateTime(value)
    except (TypeError, ValueError, DateTimeError):
        return to_date(default)
685170
def TAF_datetime_to_datetime_object(
    datetime_string             = None,
    datetime_for_year_and_month = None  # e.g. datetime.datetime.utcnow()
    ):

    

    if datetime_string.endswith("24"):

        datetime_string = datetime_string[:-2] + "00"

        tmp = datetime.datetime.strptime(datetime_string, "%d%H") +\
              datetime.timedelta(days = 1)

    else:

        tmp = datetime.datetime.strptime(datetime_string, "%d%H")

    return datetime.datetime(
        datetime_for_year_and_month.year,
        datetime_for_year_and_month.month,
        tmp.day,
        tmp.hour,
        tmp.minute
    )
1359131
def cast_datetime(ts, fmt=None):
    """"""
    dt = datetime.datetime.fromtimestamp(ts)
    if fmt:
        return dt.strftime(fmt)
    return dt
649792
def date_to_datetime(d):
    
    if not isinstance(d, datetime):
        d = datetime.combine(d, datetime.min.time())
    return d
1375046
def Datetime(null=True, **kwargs):
    """"""
    return Property(
        types=datetime.datetime,
        convert=util.local_timezone,
        load=dateutil.parser.parse,
        null=null,
        **kwargs
    )
665693
def iso8601_datetime(d):
    
    if d == values.unset:
        return d
    elif isinstance(d, datetime.datetime) or isinstance(d, datetime.date):
        return d.strftime('%Y-%m-%dT%H:%M:%SZ')
    elif isinstance(d, str):
        return d
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
1277752
def from_date_time_string(cls, datetime_string, leap_year=False):
        
        dt = datetime.strptime(datetime_string, '%d %b %H:%M')
        return cls(dt.month, dt.day, dt.hour, dt.minute, leap_year)
158617
def datetime(self, field=None, val=None):
        
        if val is None:
            def source():
                tzinfo = get_default_timezone() if settings.USE_TZ else None
                return datetime.fromtimestamp(randrange(1, 2100000000),
                                              tzinfo)
        else:
            def source():
                tzinfo = get_default_timezone() if settings.USE_TZ else None
                return datetime.fromtimestamp(int(val.strftime("%s")) +
                                              randrange(-365*24*3600*2, 365*24*3600*2),
                                              tzinfo)
        return self.get_allowed_value(source, field)
398547
def _str_to_time(self, str_value):
        """"""
        match = self.rx_time.match(str_value.upper())
        if not match:
            return None
        try:
            gd = match.groupdict()
            hour = int(gd['hour'])
            minute = int(gd['minute'])
            second = int(gd['second'] or 0)
            if gd['tt'] == 'PM':
                hour += 12
            return datetime.time(hour, minute, second)
        except (ValueError, TypeError):
            return None
1055759
def date(self, pattern='%Y-%m-%d', end_datetime=None):
        
        return self.date_time(end_datetime=end_datetime).strftime(pattern)
433877
def parse_datetime(v, default=None, tz=None, exceptions: bool=True) -> datetime:
    
    try:
        t = dateutil_parse(v, default=datetime(2000, 1, 1))
        if tz is None:
            tz = pytz.utc
        return t if t.tzinfo else tz.localize(t)
    except Exception:
        if exceptions:
            raise ValidationError('Failed to parse datetime from "{}"'.format(v))
        return default
716565
def _get_end_time(self, start_time: datetime) -> datetime:
        
        if Type.is_type_equal(self._schema.window_type, Type.DAY):
            return start_time + timedelta(days=self._schema.window_value)
        elif Type.is_type_equal(self._schema.window_type, Type.HOUR):
            return start_time + timedelta(hours=self._schema.window_value)
605274
def _construct_timeseries(self, timeseries, constraints={}):
        
        self.response_from(timeseries, constraints)
        if self.response == None:
            return None
        return {'data':self.response['data'],
                'period':self.response['period'],
                'start time':datetime.datetime.fromtimestamp(self.response['start_time']),
                'end time':datetime.datetime.fromtimestamp(self.response['end_time'])}
1351465
def to_date_or_datetime(value, ctx):
    
    if isinstance(value, str):
        temporal = ctx.get_date_parser().auto(value)
        if temporal is not None:
            return temporal
    elif type(value) == datetime.date:
        return value
    elif isinstance(value, datetime.datetime):
        return value.astimezone(ctx.timezone)

    raise EvaluationError("Can't convert '%s' to a date or datetime" % str(value))
352516
def _parsed_string_to_bounds(date_type, resolution, parsed):
    
    if resolution == 'year':
        return (date_type(parsed.year, 1, 1),
                date_type(parsed.year + 1, 1, 1) - timedelta(microseconds=1))
    elif resolution == 'month':
        if parsed.month == 12:
            end = date_type(parsed.year + 1, 1, 1) - timedelta(microseconds=1)
        else:
            end = (date_type(parsed.year, parsed.month + 1, 1) -
                   timedelta(microseconds=1))
        return date_type(parsed.year, parsed.month, 1), end
    elif resolution == 'day':
        start = date_type(parsed.year, parsed.month, parsed.day)
        return start, start + timedelta(days=1, microseconds=-1)
    elif resolution == 'hour':
        start = date_type(parsed.year, parsed.month, parsed.day, parsed.hour)
        return start, start + timedelta(hours=1, microseconds=-1)
    elif resolution == 'minute':
        start = date_type(parsed.year, parsed.month, parsed.day, parsed.hour,
                          parsed.minute)
        return start, start + timedelta(minutes=1, microseconds=-1)
    elif resolution == 'second':
        start = date_type(parsed.year, parsed.month, parsed.day, parsed.hour,
                          parsed.minute, parsed.second)
        return start, start + timedelta(seconds=1, microseconds=-1)
    else:
        raise KeyError