Return datetime object from timestamp in Excel serial format.

    Convert LSM time stamps.

    >>> excel_datetime(40237.029999999795)
    datetime.datetime(2010, 2, 28, 0, 43, 11, 999982)
546725
def excel_datetime(timestamp, epoch=None):
    
    if epoch is None:
        epoch = datetime.datetime.fromordinal(693594)
    return epoch + datetime.timedelta(timestamp)
234852
def timestamp2date(tstamp):
    ""
    dt = datetime.fromtimestamp(tstamp)
    if not dt.hour+dt.minute+dt.second+dt.microsecond:
        return dt.date()
    else:
        return dt
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
    )
119352
def to_datetime(date_or_datetime):
    
    if isinstance(date_or_datetime, date) and \
            not isinstance(date_or_datetime, datetime):
        d = date_or_datetime
        return datetime.strptime(
            '%04d-%02d-%02d' % (d.year, d.month, d.day), '%Y-%m-%d')
    return date_or_datetime
573927
def timestamp_datetime(self, timestamp):
        
        format = '%Y-%m-%d %H:%M:%S'
        # timestamp为传入的值为时间戳(10位整数)，如：1332888820
        timestamp = time.localtime(timestamp)
        ## 经过localtime转换后变成
        ## time.struct_time(tm_year=2012, tm_mon=3, tm_mday=28, tm_hour=6, tm_min=53, tm_sec=40, tm_wday=2, tm_yday=88, tm_isdst=0)
        # 最后再经过strftime函数转换为正常日期格式。
        return time.strftime(format, timestamp)
38193
def from_datetime(self, dt):
        
        global _last_timestamp

        epoch = datetime(1970, 1, 1, tzinfo=dt.tzinfo)
        offset = epoch.tzinfo.utcoffset(epoch).total_seconds() if epoch.tzinfo else 0
        timestamp = (dt  - epoch).total_seconds() - offset

        node = None
        clock_seq = None

        nanoseconds = int(timestamp * 1e9)
        timestamp = int(nanoseconds // 100) + 0x01b21dd213814000

        if clock_seq is None:
            import random
            clock_seq = random.randrange(1 << 14)  # instead of stable storage
        time_low = timestamp & 0xffffffff
        time_mid = (timestamp >> 32) & 0xffff
        time_hi_version = (timestamp >> 48) & 0x0fff
        clock_seq_low = clock_seq & 0xff
        clock_seq_hi_variant = (clock_seq >> 8) & 0x3f
        if node is None:
            node = getnode()
        return pyUUID(fields=(time_low, time_mid, time_hi_version,
                            clock_seq_hi_variant, clock_seq_low, node), version=1)
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.')
434004
def iso8601_datetime(s):
    
    try:
        return datetime.datetime.strptime(s, ISO8601_DATETIME_FORMAT).replace(tzinfo=pytz.utc)
    except (TypeError, ValueError):
        return s
401007
def from_datetime(dt, machine_id=0):
        
        td = dt - Timestamp._EPOCH
        seconds = td.days * 3600 * 24
        seconds += td.seconds
        return Timestamp(seconds, td.microseconds*1000, machine_id)
1205671
def _convert_to_datetime(unix_timestamp):
    '''
    
    '''
    try:
        unix_timestamp = float(unix_timestamp)
        return datetime.fromtimestamp(unix_timestamp).strftime('%Y-%m-%d %H:%M:%S')
    except (ValueError, TypeError):
        return 'Invalid Timestamp'
584583
def to_datetime(timestamp):
    """"""
    return dt.fromtimestamp(time.mktime(
        time.localtime(int(str(timestamp)[:10]))))
61812
def to_ts(date: datetime.date) -> float:
    
    return datetime.datetime(
        date.year, date.month, date.day,
        tzinfo=datetime.timezone.utc).timestamp()
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)
27828
def convert_datetime_type(obj):
    ''' 

    '''
    # Pandas NaT
    if pd and obj is pd.NaT:
        return np.nan

    # Pandas Period
    if pd and isinstance(obj, pd.Period):
        return obj.to_timestamp().value / 10**6.0

    # Pandas Timestamp
    if pd and isinstance(obj, _pd_timestamp): return obj.value / 10**6.0

    # Pandas Timedelta
    elif pd and isinstance(obj, pd.Timedelta): return obj.value / 10**6.0

    # Datetime (datetime is a subclass of date)
    elif isinstance(obj, dt.datetime):
        diff = obj.replace(tzinfo=None) - DT_EPOCH
        return diff.total_seconds() * 1000.

    # Date
    elif isinstance(obj, dt.date):
        return (dt.datetime(*obj.timetuple()[:6]) - DT_EPOCH).total_seconds() * 1000

    # NumPy datetime64
    elif isinstance(obj, np.datetime64):
        epoch_delta = obj - NP_EPOCH
        return (epoch_delta / NP_MS_DELTA)

    # Time
    elif isinstance(obj, dt.time):
        return (obj.hour * 3600 + obj.minute * 60 + obj.second) * 1000 + obj.microsecond / 1000.
1161540
def timestamp_to_datetime(cls, dt, dt_format=DATETIME_FORMAT):
        """"""
        return cls.convert_datetime(cls.get_datetime(dt), dt_format=dt_format)
1204504
def dtstr_to_datetime(dtstr, to_tz=None, fail_silently=True):
    
    try:
        dt = datetime.datetime.utcfromtimestamp(int(dtstr, 36) / 1e3)
        if to_tz:
            dt = timezone.make_aware(dt, timezone=pytz.UTC)
            if to_tz != pytz.UTC:
                dt = dt.astimezone(to_tz)
        return dt
    except ValueError, e:
        if not fail_silently:
            raise e
        return None
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