convert from iso datetime to user format
166131
protected function isodatetimeToHuman($isodatetime)
    {
        $datetime = \DateTime::createFromFormat( $this->store_as, $isodatetime);
        if (!$datetime) return '';
        $timestamp = $datetime->getTimestamp();
        if ($timestamp < 1) {
            return "";
        }
        $isodatetime = date($this->format, $timestamp);

        return $isodatetime;
    }
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())
        }
243133
def to_datetime(t):
    
    if t is None:
        return None

    # extract values
    year, mon, day, h, m, s = t

    # assume the values are valid
    try:
        return datetime(year, mon, day, h, m, s)
    except ValueError:
        pass

    # sanitize invalid values
    mday = (0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
    if mon < 1:
        mon = 1
    if mon > 12:
        mon = 12
    if day < 1:
        day = 1
    if day > mday[mon]:
        day = mday[mon]
    if h > 23:
        h = 23
    if m > 59:
        m = 59
    if s > 59:
        s = 59
    if mon == 2 and day == 29:
        try:
            return datetime(year, mon, day, h, m, s)
        except ValueError:
            day = 28
    return datetime(year, mon, day, h, m, s)
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
838469
def _(obj):
    """"""

    tz_offset = obj.utcoffset()

    if not tz_offset or tz_offset == UTC_ZERO:
        iso_datetime = obj.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
    else:
        iso_datetime = obj.isoformat()

    return iso_datetime
163629
def to_datetime(plain_date, hours=0, minutes=0, seconds=0, ms=0):
    """"""
    # don't mess with datetimes
    if isinstance(plain_date, datetime.datetime):
        return plain_date
    return datetime.datetime(
        plain_date.year,
        plain_date.month,
        plain_date.day,
        hours,
        minutes,
        seconds,
        ms,
    )
714980
def week_to_datetime(iso_year, iso_week):
    ""
    gregorian = iso_to_gregorian(iso_year, iso_week, 0)
    return datetime.datetime.combine(gregorian, datetime.time(0))
234370
def from_iso_datetime(datetimestring, use_dateutil=True):
    
    if not _iso8601_datetime_re.match(datetimestring):
        raise ValueError('Not a valid ISO8601-formatted datetime string')
    # Use dateutil's parser if possible
    if dateutil_available and use_dateutil:
        return parser.isoparse(datetimestring)
    else:
        # Strip off timezone info.
        return datetime.datetime.strptime(datetimestring[:19], '%Y-%m-%dT%H:%M:%S')
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
391401
def convert_iso_stamp(t, tz=None):
    """"""

    if t is None:
        return None

    dt = dateutil.parser.parse(t)
    if tz is not None:
        timezone = pytz.timezone(tz)
        if dt.tzinfo is None:
            dt = timezone.localize(dt)
    return dt
1337481
def formatIBDatetime(dt) -> str:
    
    if not dt:
        s = ''
    elif isinstance(dt, datetime.datetime):
        if dt.tzinfo:
            # convert to local system timezone
            dt = dt.astimezone()
        s = dt.strftime('%Y%m%d %H:%M:%S')
    elif isinstance(dt, datetime.date):
        s = dt.strftime('%Y%m%d 23:59:59')
    else:
        s = dt
    return s
701704
def to_datetime(date):
    """"""
    return datetime.datetime(date.year, date.month, date.day)
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
    )
206504
def serialize(obj):
    """"""
    from datetime import datetime, date, time
    if isinstance(obj, date) and not isinstance(obj, datetime):
        obj = datetime.combine(obj, time.min)
    if isinstance(obj, datetime):
        return obj.isoformat()
1149233
def _get_date_time_format(dt_string):
    '''
    
    '''
    valid_formats = [
        '%I:%M:%S %p',
        '%I:%M %p',
        '%H:%M:%S',
        '%H:%M',
        '%Y-%m-%d',
        '%m-%d-%y',
        '%m-%d-%Y',
        '%m/%d/%y',
        '%m/%d/%Y',
        '%Y/%m/%d'
    ]
    for dt_format in valid_formats:
        try:
            datetime.strptime(dt_string, dt_format)
            return dt_format
        except ValueError:
            continue
    return False
214181
def iso8601(self, tzinfo=None, end_datetime=None):
        
        return self.date_time(tzinfo, end_datetime=end_datetime).isoformat()
140851
def iso_date(d) -> str:
        
        if isinstance(d, datetime):
            return d.isoformat()
        elif isinstance(d, date):
            return datetime.combine(d, datetime.min.time()).isoformat()
        else:
            try:
                datetime.strptime(d, '%Y-%m-%dT%H:%M:%S')
                return d
            except ValueError:
                try:
                    datetime.strptime(d, '%Y-%m-%d')
                    return d + "T00:00:00"
                except ValueError:
                    pass
        raise ISODateError("Can not convert value to ISO format for kg")