python/np/pd日期相互转换类封装(tcy)

阅读 115

2022-03-10

Date类主要用于日期的转换,用于金融模型的时间转换

class Date(object):
    def is_holiday(date: 'datetime or date'):
    def get_workdays(start: 'datetime or date',end: 'datetime or date') -> 'list[datetime.date]':
    def latest_working_day(n: int = None,backstr=True,separator=False) -> str:
    def get_cur_workdays_idx(hour, today, lst):
    def datetime_to_str(dt: datetime, separator=True, **kwargs):
     
    # 把字符串转成datetime
    def str_to_datetime(st: str, separator=True, **kwargs):
    def date_to_str(date, separator=True, **kwargs):
    def str_to_date(date: str, separator=True, **kwargs):
     
    # 把时间戳转成字符串形式
    def time_to_str(timestamp: 'float or struct_time',separator=True,**kwargs):
        
    # 把字符串转成时间戳形式
    def str_to_time(strtime: str,separator=True,back_struct_time=False,**kwargs):
    def datetime_to_date(dt: 'datetime'):

    # 把datetime类型转时间戳形式
    def datetime_to_time(dt: 'datetime', back_struct_time=False):
    def date_to_datetime(date: 'date'):
    def date_to_time(date: 'date', back_struct_time=False):
    def time_to_datetime(timestamp: 'float or struct_time',separator=True,**kwargs):
    def time_to_date(timestamp: 'float or struct_time'):
       
    # datetime转Timestamp
    def datetime_to_timestamp(dt: 'datetime or date or str or [str] or Series',
        unit: str = None,format: 'str | None' = None,errors: 'str' = 'raise'):
      
    # date转Timestamp
    def date_to_timestamp(dt: 'date'):
      
    # time转Timestamp
    def time_to_timestamp(ts: 'float or time.struct_time'):
     
    # str转Timestamp
    def str_to_timestamp(dt: str, unit='ns'):
     
    # Timestamp转datetime
    def timestamp_to_datetime(ts: 'str or Timestamp or date_range'):
     
    # Timestamp转date
    def timestamp_to_date(ts: 'Timestamp'):
    # Timestamp转time
    def timestamp_to_time(ts: 'Timestamp', back_struct_time=False):
      
    # Timestamp转str
    def timestamp_to_str(ts: 'Timestamp', separator=True, **kwargs):
      
    # Timestamp转datetime64
    def timestamp_to_datetime64(ts: 'str or Timestamp', unit='ns'):
     
    def str_to_datetime64(dt: 'str or int', unit='ns'):
      
    # datetime转np.datetime64
    def datetime_to_datetime64(dt: 'datetime or date'):
      
    # date转np.datetime64
    def date_to_datetime64(dt: 'datetime or date'):
     
    # time转np.datetime64
    def time_to_datetime64(tp: 'time'):
      
    # np.datetime64[s]转datetime.datetime
    def datetime64_to_datetime(dt64: 'str or np.datetime64'):
     
    # np.datetime64[s]转datetime.date
    def datetime64_to_date(dt64: 'str or np.datetime64'):
      
    # np.datetime64[s]转time
    def datetime64_to_time(dt64: 'str or np.datetime64',back_struct_time=False):
    # np.datetime64[]转Timestamp
    def datetime64_to_timestamp(dt64: 'str or number or np.datetime64',unit: str = None):
    def datetime64_convert(dt64: 'np.datetime64', unit: str = 'ns'):


def test_workdays():
def test_date():
def test_pd_np_python_date():
    
if __name__ == '__main__':
test_workdays()
test_date()
test_pd_np_python_date() 
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# @Project:TcyQuantTrade
# @Module:date

# @Author:       tcy
# @Date:         2022/2/3  23:54
# @Emial:        3615693665@qq.com
# @Version:     1.18
# @Last Modified time:
# @City:           China Shanghai Songjiang Xiaokunshan
# @Company:  Weishi Machinery Manufacturing Priority

import time
import datetime
import numpy as np
import pandas as pd
import chinese_calendar as cn_calendar


class Date(object):
    # dt_format = '%Y-%m-%d %H:%M:%S'
    # dt_format_no = '%Y%m%d%H%M%S'
    # date_format = '%Y-%m-%d'
    # date_format_no = '%Y%m%d'

    @staticmethod
    def is_holiday(date: 'datetime or date'):
        return cn_calendar.is_holiday(date) 
    @staticmethod
    def get_workdays(start: 'datetime or date',
                     end: 'datetime or date') -> 'list[datetime.date]':
        '''
        get_workdays(start, end)->list[datetime.date]
        用途:获取开始日期和结束日期之间的工作日(包括开始日期和结束日期)
        参数: start,end: datetime.date | datetime.datetime
        '''
        return cn_calendar.get_workdays(start, end)

   
    @staticmethod
    def latest_working_day(
            n: int = None,
            backstr=True,
            separator=False) -> str:
        '''
        用途:距离先在的最近的一个工作日
        n:int 距离今天(工作日,距离今天最近的工作日)的天数
            负值从向前取值,-1上一个工作日,-2上上个工作日
            正值从向后取值,1下一个工作日,2下下个工作日
            0 距离今天最近的工作日
        '''
        def get_cur_workdays_idx(hour, today, lst):
            idx = 0
            if today in lst:
                idx = lst.index(today)
            else:
                low = False
                for i, v in enumerate(lst):
                    if v < today:
                        low = True
                    if low and v > today:
                        idx = i - 1 if hour < 12 else i
                        break
            return idx

        now = datetime.datetime.now()
        today = now.date()
        start = today - datetime.timedelta(days=60)
        end = today + datetime.timedelta(days=60)
        lst = cn_calendar.get_workdays(start, end)
        idx = get_cur_workdays_idx(now.hour, today, lst)
        cur_workdays = lst[idx]

        if not n:
            date = cur_workdays
        else:
            date = lst[idx + n]

        if not backstr:
            return date
        return Date.date_to_str(date, separator)
    @staticmethod
    def _datetime_str_format(separator=True, **kwargs):
        if 'format' in kwargs:
            format = kwargs['format']
        elif separator:
            format = '%Y-%m-%d %H:%M:%S'
        else:
            format = '%Y%m%d%H%M%S'

        return format

    @staticmethod
    def _date_str_format(separator=True, **kwargs):
        if 'format' in kwargs:
            format = kwargs['format']
        elif separator:
            format = '%Y-%m-%d'
        else:
            format = '%Y%m%d'

        return format
    # 把datetime转成字符串
    @staticmethod
    def datetime_to_str(dt: datetime, separator=True, **kwargs):
        '''
        参数:
        dt: datetime.datetime
        separator=True,输出的字符串格式
            True输出默认的字符串格式;format= '%Y-%m-%d %H:%M:%S'
            False输出字符串无分隔符 format=  '%Y%m%d%H%M%S'
        **kwargs:
            keys='format 输出字符串的格式;若指定此参数忽略separator参数

        return:str
        '''
        format = Date._datetime_str_format(separator, **kwargs)
        return dt.strftime(format=format)

    # 把字符串转成datetime
    @staticmethod
    def str_to_datetime(st: str, separator=True, **kwargs):
        '''
        参数:
        st: str日期字符串
        separator=True,输出的字符串格式
            True输出默认的字符串格式;format= '%Y-%m-%d %H:%M:%S'
            False输出字符串无分隔符 format=  '%Y%m%d%H%M%S'
        **kwargs:
            keys='format 输出字符串的格式;若指定此参数忽略separator参数

        return:str
        '''
        format = Date._datetime_str_format(separator, **kwargs)
        return datetime.datetime.strptime(st, format)

    @staticmethod
    def date_to_str(date, separator=True, **kwargs):
        '''
       参数:
       date: datetime.date
       separator=True,输出的字符串格式
           True输出默认的字符串格式;format= '%Y-%m-%d'
           False输出字符串无分隔符 format=  '%Y%m%d'
       **kwargs:
           keys='format 输出字符串的格式;若指定此参数忽略separator参数

       return:str
       '''
        format = Date._date_str_format(separator, **kwargs)
        return date.strftime(format=format)

    @staticmethod
    def str_to_date(date: str, separator=True, **kwargs):
        '''
        参数:
        date: str日期字符串
        separator=True,输出的字符串格式
            True输出默认的字符串格式;format= '%Y-%m-%d'
            False输出字符串无分隔符 format=  '%Y%m%d'
        **kwargs:
            keys='format 输出字符串的格式;若指定此参数忽略separator参数

        return:str
        '''
        _format = Date._date_str_format(separator, **kwargs)
        return datetime.datetime.strptime(date, _format).date()
    # 把时间戳转成字符串形式
    @staticmethod
    def time_to_str(
            timestamp: 'float or struct_time',
            separator=True,
            **kwargs):
        ''' used: 把时间戳转化为时间: 1479264792 to 2020-11-16 10:53:12'''
        '''
        参数:
        timestamp: int or float or struct_time
        separator=True,输出的字符串格式
            True输出默认的字符串格式;format= '%Y-%m-%d %H:%M:%S'
            False输出字符串无分隔符 format=  '%Y%m%d%H%M%S'
        **kwargs:
            keys='format 输出字符串的格式;若指定此参数忽略separator参数

        return:str
        '''
        format = Date._datetime_str_format(separator, **kwargs)
        if isinstance(timestamp, (float, int)):
            timestamp = time.localtime(timestamp)
        return time.strftime(format, timestamp)

    # 把字符串转成时间戳形式
    @staticmethod
    def str_to_time(
            strtime: str,
            separator=True,
            back_struct_time=False,
            **kwargs):
        '''
        参数:
        time: str时间字符串
        separator=True,输出的字符串格式
            True输出默认的字符串格式;format= '%Y-%m-%d %H:%M:%S'
            False输出字符串无分隔符 format=  '%Y%m%d%H%M%S'
        **kwargs:
            keys='format 输出字符串的格式;若指定此参数忽略separator参数

        return:str
        '''
        format = Date._datetime_str_format(separator, **kwargs)
        st = time.strptime(strtime, format)
        if back_struct_time:
            return st
        return time.mktime(st)

    @staticmethod
    def datetime_to_date(dt: 'datetime'):
        return datetime.date(dt.year, dt.month, dt.day)

    # 把datetime类型转时间戳形式
    @staticmethod
    def datetime_to_time(dt: 'datetime', back_struct_time=False):
        if back_struct_time:
            return dt.timetuple()
        return time.mktime(dt.timetuple())

    @staticmethod
    def date_to_datetime(date: 'date'):
        return datetime.datetime(date.year, date.month, date.day)

    @staticmethod
    def date_to_time(date: 'date', back_struct_time=False):
        if back_struct_time:
            return date.timetuple()
        return time.mktime(date.timetuple())

    @staticmethod
    def time_to_datetime(
            timestamp: 'float or struct_time',
            separator=True,
            **kwargs):
        '''
        参数:
        timestamp: time float (如time.time()) or time_struct_time(如time.localtime())
        separator=True,输出的字符串格式
            True输出默认的字符串格式;format= '%Y-%m-%d %H:%M:%S'
            False输出字符串无分隔符 format=  '%Y%m%d%H%M%S'
        **kwargs:
            keys='format 输出字符串的格式;若指定此参数忽略separator参数

        return:str
        '''
        format = Date._datetime_str_format(separator, **kwargs)
        if isinstance(timestamp, (float, int)):
            timestamp = time.localtime(timestamp)
        st = time.strftime(format, timestamp)
        return datetime.datetime.strptime(st, format)

    @staticmethod
    def time_to_date(timestamp: 'float or struct_time'):
        if isinstance(timestamp, (float, int)):
            timestamp = time.localtime(timestamp)
        t = timestamp
        return datetime.date(t.tm_year, t.tm_mon, t.tm_mday)

    # ===================================================
    # datetime转Timestamp
    @staticmethod
    def datetime_to_timestamp(
            dt: 'datetime or date or str or [str] or Series',
            unit: str = None,
            format: 'str | None' = None,
            errors: 'str' = 'raise'):
        '''
        实例1:
        pd.to_datetime('2018-10-26 12:00 -0530')#Timestamp('2018-10-26 12:00:00-0530', tz='pytz.FixedOffset(-330)')
        pd.to_datetime('20181026123059')#Timestamp('2018-10-26 12:30:59')
        pd.to_datetime('201810261230590530')#OverflowError
        pd.to_datetime('2018/10/26 12:30:59')#Timestamp('2018-10-26 12:30:59')

        pd.to_datetime(1490195805, unit='s')                    #Timestamp('2017-03-22 15:16:45')
        pd.to_datetime(1490195805433502912, unit='ns')#Timestamp('2017-03-22 15:16:45.433502912')
        pd.to_datetime('13000101', format='%Y%m%d', errors='ignore')  #datetime.datetime(1300, 1, 1, 0, 0)
        pd.to_datetime('13000101', format='%Y%m%d', errors='coerce') #NaT

        实例2:
        s = pd.Series(['3/11/2000', '3/12/2000', '3/13/2000'] )
        pd.to_datetime(s, infer_datetime_format=True)#加速解析,默认False

        实例3:
        pd.to_datetime([1, 2, 3], unit='D', origin=pd.Timestamp('1960-01-01'))
        #DatetimeIndex(['1960-01-02', '1960-01-03', '1960-01-04'],dtype='datetime64[ns]', freq=None)

        pd.to_datetime(['2018-10-26 12:00 -0530', '2018-10-26 12:00 -0500'])
        #Index([2018-10-26 12:00:00-05:30, 2018-10-26 12:00:00-05:00], dtype='object')

        pd.to_datetime(['2018-10-26 12:00 -0530', '2018-10-26 12:00 -0500'], utc=True)
        #DatetimeIndex(['2018-10-26 17:30:00+00:00', '2018-10-26 17:00:00+00:00'],dtype='datetime64[ns, UTC]', freq=None)

        转换方法:
        #方法1
        pd.Timestamp(dt)  #Timestamp('2022-02-27 22:29:43.717165')

        #方法2
        pd.to_datetime(dt) #Timestamp('2022-02-27 22:29:43.717165')

        #方法3
        ts=pd.DatetimeIndex([dt])[0] #Timestamp('2022-02-27 22:29:43.717165')
        '''
        return pd.to_datetime(dt, unit=unit, format=format, errors=errors,
                              infer_datetime_format=True)

    # date转Timestamp
    @staticmethod
    def date_to_timestamp(dt: 'date'):
        '''
        参考pd.to_datetime()
        '''
        return pd.to_datetime(dt)

    # time转Timestamp
    @staticmethod
    def time_to_timestamp(ts: 'float or time.struct_time'):
        '''
        实例:
        创建Timestam
        pd.Timestamp(1239.1238934)#default to ns
        #Timestamp('1970-01-01 00:00:00.000001239')

        pd.Timestamp(1239.1238934,unit='D')#change units
        #Timestamp('1973-05-24 02:58:24.389760')
        '''
        if isinstance(ts, (int, float)):
            ts = time.localtime(ts)
        return pd.Timestamp(
            year=ts.tm_year,
            month=ts.tm_mon,
            day=ts.tm_mday,
            hour=ts.tm_hour,
            minute=ts.tm_min,
            second=ts.tm_sec)

    # str转Timestamp

    @staticmethod
    def str_to_timestamp(dt: str, unit='ns'):
        '''
        实例:
        #str转为时间戳
        pd.Timestamp('2019-06-30 16')
        # Timestamp('2019-06-30 16:00:00')

        pd.to_datetime(['2019-7-1','2019-7-2'])
        #DatetimeIndex(['2019-07-01', '2019-07-02'], dtype='datetime64[ns]', freq=None)
        '''
        return pd.Timestamp(dt, unit=unit)

    # Timestamp转datetime
    @staticmethod
    def timestamp_to_datetime(ts: 'str or Timestamp or date_range'):
        '''
        从时间戳中获取日期时间
        ts=pd.Timestamp('2019-06-30 04:24:33.545632')#Timestamp('2019-06-30 04:24:33.545632')
        ts.to_datetime()#AttributeError: 'Timestamp' object has no attribute 'to_datetime'

        ts.to_pydatetime() # datetime.datetime(2019, 6, 30, 4, 24, 33, 545632)

        #将日期列表转为datetime格式
        pd.date_range('20190701','20190702',freq='D').to_pydatetime()
        #array([datetime.datetime(2019, 7, 1, 0, 0),datetime.datetime(2019, 7, 2, 0, 0)], dtype=object)

        #支持时区
        pd.date_range('20190701','20190702',freq='D').tz_localize('UTC').tz_convert('Australia/Sydney').to_pydatetime()
        Out[123]:
        array([datetime.datetime(2019, 7, 1, 10, 0, tzinfo=<DstTzInfo 'Australia/Sydney' AEST+10:00:00 STD>),
               datetime.datetime(2019, 7, 2, 10, 0, tzinfo=<DstTzInfo 'Australia/Sydney' AEST+10:00:00 STD>)],
              dtype=object)
        '''
        if isinstance(ts, str):
            ts = pd.Timestamp(ts)
        return ts.to_pydatetime()

    # Timestamp转date
    @staticmethod
    def timestamp_to_date(ts: 'Timestamp'):
        '''
        参考 ts.to_pydatetime() # datetime.datetime(2019, 6, 30, 4, 24, 33, 545632)
        '''
        return ts.to_pydatetime().date()

    # Timestamp转time
    @staticmethod
    def timestamp_to_time(ts: 'Timestamp', back_struct_time=False):
        if back_struct_time:
            return ts.timetuple()
        return time.mktime(ts.timetuple())

    # Timestamp转str
    @staticmethod
    def timestamp_to_str(ts: 'Timestamp', separator=True, **kwargs):
        '''
        参数:
        ts: 'Timestamp',
        separator=True,输出的字符串格式
        True输出默认的字符串格式;format= '%Y-%m-%d %H:%M:%S'
        False输出字符串无分隔符 format=  '%Y%m%d%H%M%S'
        **kwargs:
        keys='format 输出字符串的格式;若指定此参数忽略separator参数

        return:str
        '''
        format = Date._datetime_str_format(separator, **kwargs)
        return ts.strftime(format)

    # Timestamp转datetime64
    @staticmethod
    def timestamp_to_datetime64(ts: 'str or Timestamp', unit='ns'):
        '''
        实例:
        ts.to_datetime64()
        #numpy.datetime64('2022-02-27T22:29:43.717165000')
        '''
        if isinstance(ts, str):
            ts = pd.Timestamp(ts)
        dt64 = ts.to_datetime64()
        if unit == 'ns':
            return dt64
        return np.datetime64(dt64, unit)
        # return dt64.astype('datetime64[%s]'%unit)

    @staticmethod
    def str_to_datetime64(dt: 'str or int', unit='ns'):
        '''
        3.numpy库
        NumPy没有单独的日期和时间对象,只有一个datetime64对象来表示单个时刻。
        datetime模块的datetime对象具有微秒精度(百万分之一秒)。
        NumPy的datetime64对象允许您将其精度从小时数一直设置为阿秒(10 ^ -18)。
        它的构造函数更灵活,可以采用各种输入。

        3.1)创建numPy的datetime64和timedelta64对象

        #1 datetime64
        np.datetime64(5,'ns')
        #numpy.datetime64('1970-01-01T00:00:00.000000005')

        np.datetime64(150887504,'s')
        #numpy.datetime64('1974-10-13T09:11:44')

        np.datetime64('2019-06-30')
        #numpy.datetime64('2019-06-30')

        #2.Timedeltas
        np.timedelta64(5,'D')#5 days
        # numpy.timedelta64(5,'D')

        np.timedelta64(10,'h')#10 hours
        #numpy.timedelta64(10,'h')

        #通过减去两个datetime64来创建
        np.datetime64('2019-06-30T05:30:45.67')-np.datetime64('2017-10-22T12:30:45.67')
        #numpy.timedelta64(53197200000,'ms')
        '''
        return np.datetime64(dt, unit)

    # datetime转np.datetime64
    @staticmethod
    def datetime_to_datetime64(dt: 'datetime or date'):
        '''
        实例:
        dt64=np.datetime64(dt) #numpy.datetime64('2022-02-27T22:29:43.717165')
        dt64.dtype# dtype('<M8[us]')
        np.datetime64(datetime.datetime.utcnow()) #numpy.datetime64('2022-02-27T14:32:34.661203')
        '''
        return np.datetime64(dt)

    # date转np.datetime64
    @staticmethod
    def date_to_datetime64(dt: 'datetime or date'):
        '''
        实例:
        dt64=np.datetime64(dt) #numpy.datetime64('2022-02-27T22:29:43.717165')
        dt64.dtype# dtype('<M8[us]')
        np.datetime64(datetime.datetime.utcnow()) #numpy.datetime64('2022-02-27T14:32:34.661203')
        '''
        return np.datetime64(dt)

    # time转np.datetime64
    @staticmethod
    def time_to_datetime64(tp: 'time'):
        dt = Date.time_to_datetime(tp)
        return np.datetime64(dt)

    # np.datetime64[s]转datetime.datetime
    @staticmethod
    def datetime64_to_datetime(dt64: 'str or np.datetime64'):
        '''
        np.datetime64[s]转datetime.datetime

        #方法1
        unix_epoch=np.datetime64(0,'s')
        one_second=np.timedelta64(1,'s')
        second_since_epoch=(dt64-unix_epoch)/one_second
        second_since_epoch#1646000983.717165

        datetime.datetime.utcfromtimestamp(second_since_epoch)
        #datetime.datetime(2022, 2, 27, 22, 29, 43, 717165)

        #方法2
        dt64.item()
        #datetime.datetime(2022, 2, 27, 22, 29, 43, 717165)

        #方法3
        #对于单个datetime64它返回单个datetime

        dt64.tolist()
        #datetime.datetime(2022, 2, 27, 22, 29, 43, 717165)

        #方法4
        np.datetime64(datetime.datetime.utcnow()).astype(datetime.datetime)
        #datetime.datetime(2022, 2, 27, 14, 55, 15, 863305)

        #方法5
        dt64_3=np.datetime64('2002-06-28T01:00:00.000000000+0100','s')
        #numpy.datetime64('2002-06-28T00:00:00')

        datetime.datetime.utcfromtimestamp(dt64_3.astype(int))
        #datetime.datetime(2002, 6, 28, 0, 0)
        '''
        if isinstance(dt64, str):
            dt64 = np.datetime64(dt64)
        return dt64.tolist()

    # np.datetime64[s]转datetime.date
    @staticmethod
    def datetime64_to_date(dt64: 'str or np.datetime64'):
        '''
        np.datetime64[s]转datetime.datetime

        #方法1
        unix_epoch=np.datetime64(0,'s')
        one_second=np.timedelta64(1,'s')
        second_since_epoch=(dt64-unix_epoch)/one_second
        second_since_epoch#1646000983.717165

        datetime.datetime.utcfromtimestamp(second_since_epoch)
        #datetime.datetime(2022, 2, 27, 22, 29, 43, 717165)

        #方法2
        dt64.item()
        #datetime.datetime(2022, 2, 27, 22, 29, 43, 717165)

        #方法3
        #对于单个datetime64它返回单个datetime

        dt64.tolist()
        #datetime.datetime(2022, 2, 27, 22, 29, 43, 717165)

        #方法4
        np.datetime64(datetime.datetime.utcnow()).astype(datetime.datetime)
        #datetime.datetime(2022, 2, 27, 14, 55, 15, 863305)

        #方法5
        dt64_3=np.datetime64('2002-06-28T01:00:00.000000000+0100','s')
        #numpy.datetime64('2002-06-28T00:00:00')

        datetime.datetime.utcfromtimestamp(dt64_3.astype(int))
        #datetime.datetime(2002, 6, 28, 0, 0)
        '''
        if isinstance(dt64, str):
            return np.datetime64(dt64).item().date()
        dt64 = dt64.tolist()
        if not isinstance(dt64, list):
            return dt64.date()
        return [v.date() for v in dt64]

    # np.datetime64[s]转time
    @staticmethod
    def datetime64_to_time(
            dt64: 'str or np.datetime64',
            back_struct_time=False):
        dt = Date.datetime_to_datetime64(dt64)
        return Date.datetime_to_time(dt.item(), back_struct_time)

    # np.datetime64[]转Timestamp
    @staticmethod
    def datetime64_to_timestamp(
            dt64: 'str or number or np.datetime64',
            unit: str = None):
        '''
        ------------------------------------------------------------------------------------------
        参数:
        dt64: 'str or number or np.datetime64'
        unit:str=None 仅用于数字
        ------------------------------------------------------------------------------------------
        备注:
        #方法1
        pd.to_datetime(dt64)
        # Timestamp('2022-02-27 22:29:43.717165')

        pd.to_datetime('2019-06-30T00:00:00.000000')
        #Timestamp('2019-06-30 00:00:00')

        #方法2
        pd.Timestamp(dt64)
        # Timestamp('2022-02-27 22:29:43.717165')
        '''
        return pd.to_datetime(dt64, unit=unit)

    @staticmethod
    def datetime64_convert(dt64: 'np.datetime64', unit: str = 'ns'):
        '''
        实例:np.datetime64[s]转datetime64[ns]
        np.datetime64(dt64,'ns')
        # numpy.datetime64('2022-02-27T22:29:43.717165000')
        '''
        return np.datetime64(dt64, unit)
def test_workdays():
    today = datetime.datetime.now()
    yesterday = today - datetime.timedelta(days=1)
    print('test workdays start...')
    print('1.1.is workdays=', Date.is_holiday(today))
    print('1.2.is workdays=', Date.is_holiday(yesterday))
    lst = Date.get_workdays(today, today + datetime.timedelta(days=7))
    print('1.3.workdays lst=', lst)

    print('2.1.workdays -2 =', Date.latest_working_day(-2))
    print('2.2.workdays -1 =', Date.latest_working_day(-1))
    print('2.3.workdays  =', Date.latest_working_day())
    print('2.4.workdays 0 =', Date.latest_working_day(0))
    print('2.5.workdays 1 =', Date.latest_working_day(1))
    print('2.6.workdays 1 =', Date.latest_working_day(1, False))
    print('2.7.workdays 2 =', Date.latest_working_day(2, True))
    print('2.8.workdays 2 =', Date.latest_working_day(2, True, True))

    '''
    test workdays start...
    1.1.is workdays= False
    1.2.is workdays= True
    1.3.workdays lst= [datetime.date(2022, 2, 28), datetime.date(2022, 3, 1), datetime.date(2022, 3, 2), datetime.date(2022, 3, 3), datetime.date(2022, 3, 4), datetime.date(2022, 3, 7)]
    2.1.workdays -2 = 20220224
    2.2.workdays -1 = 20220225
    2.3.workdays  = 20220228
    2.4.workdays 0 = 20220228
    2.5.workdays 1 = 20220301
    2.6.workdays 1 = 2022-03-01
    2.7.workdays 2 = 20220302
    2.8.workdays 2 = 2022-03-02
    '''
def test_date():
    # 日期时间字符串
    st = "2022-02-28 16:10:10"
    now = datetime.datetime.now()  # 当前日期时间
    today = now.date()
    t1 = time.time()  # 当前时间戳
    t2 = time.localtime()

    print('test date start...')
    print('1.1.把datetime转成字符串 s1 =', Date.datetime_to_str(now))
    print('1.2.把datetime转成字符串 s1 =', Date.datetime_to_str(now, False))
    print(
        '1.3.把datetime转成字符串 s1 =',
        Date.datetime_to_str(
            now,
            format='%Y-%m-%d'))

    print('1.4.把字符串转成datetime s2 =', Date.str_to_datetime(st))
    print(
        '1.5.把字符串转成datetime s2 =',
        Date.str_to_datetime(
            "20220228161010",
            False))
    print(
        '1.6.把字符串转成datetime s2 =',
        Date.str_to_datetime(
            "20220228",
            format='%Y%m%d'))

    today = datetime.date.today()
    print('2.1.把date转成字符串 s1 =', Date.date_to_str(today))
    print('2.2.把date转成字符串 s1 =', Date.date_to_str(today, False))
    print('2.3.把date转成字符串 s1 =', Date.date_to_str(today, format='%Y-%m'))

    print('2.4.把字符串转成date s2 =', Date.str_to_date("2022-02-28"))
    print('2.5.把字符串转成date s2 =', Date.str_to_date("20220228", False))
    print('2.6.把字符串转成date s2 =', Date.str_to_date("20220228", format='%Y%m%d'))

    print('3.1.把time转成字符串 s1 =', Date.time_to_str(time.time()))
    print('3.2.把time转成字符串 s1 =', Date.time_to_str(time.localtime()))
    print('3.3.把time转成字符串 s1 =', Date.time_to_str(time.time(), False))
    print('3.4.把time转成字符串 s1 =', Date.time_to_str(time.time(), format='%Y-%m'))

    print('3.5.把字符串转成time s2 =', Date.str_to_time("2022-02-04 00:20:17"))
    print(
        '3.6.把字符串转成time s2 =',
        Date.str_to_time(
            "2022-02-04 00:20:17",
            back_timestruct=True))
    print('3.7.把字符串转成time s2 =', Date.str_to_time("20220228002017", False))
    print('3.8.把字符串转成time s2 =', Date.str_to_time("20220228", format='%Y%m%d'))

    print('4.1.datetime_to_date(now: datetime) =', Date.datetime_to_date(now))
    print(
        '4.2.datetime_to_time(now: datetime, back_struct_time=False) =',
        Date.datetime_to_time(now))
    print(
        '4.3.datetime_to_time(now: datetime, back_struct_time=True) =',
        Date.datetime_to_time(
            now,
            True))

    print('5.1.date_to_datetime(date: date) =', Date.date_to_datetime(today))
    print(
        '5.2.datetime_to_time(now: datetime, back_struct_time=False) =',
        Date.datetime_to_time(today))
    print(
        '5.3.datetime_to_time(now: datetime, back_struct_time=True) =',
        Date.datetime_to_time(
            today,
            True))

    print(
        "6.1.time_to_datetime(timestamp: 'float or struct_time', separator=True, **kwargs) =",
        Date.time_to_datetime(t1))
    print(
        "6.2.time_to_datetime(timestamp: 'float or struct_time', separator=True, **kwargs) =",
        Date.time_to_datetime(t2))
    print(
        "6.3.time_to_datetime(timestamp: 'float or struct_time', separator=False, **kwargs) =",
        Date.time_to_datetime(
            t2,
            False))
    print(
        "6.4.time_to_datetime(timestamp: 'float or struct_time', separator=True, **kwargs) =",
        Date.time_to_datetime(
            t2,
            format='%Y%m%d'))

    print(
        "7.1.time_to_date(timestamp: 'float or struct_time')=",
        Date.time_to_date(t1))
    print(
        "7.2.time_to_date(timestamp: 'float or struct_time')=",
        Date.time_to_date(t2))

    print()

    '''
    test date start...
    1.1.把datetime转成字符串 s1 = 2022-02-28 19:09:39
    1.2.把datetime转成字符串 s1 = 20220228190939
    1.3.把datetime转成字符串 s1 = 2022-02-28
    1.4.把字符串转成datetime s2 = 2022-02-28 16:10:10
    1.5.把字符串转成datetime s2 = 2022-02-28 16:10:10
    1.6.把字符串转成datetime s2 = 2022-02-28 00:00:00
    2.1.把date转成字符串 s1 = 2022-02-28
    2.2.把date转成字符串 s1 = 20220228
    2.3.把date转成字符串 s1 = 2022-02
    2.4.把字符串转成date s2 = 2022-02-28
    2.5.把字符串转成date s2 = 2022-02-28
    2.6.把字符串转成date s2 = 2022-02-28
    3.1.把time转成字符串 s1 = 2022-02-28 19:09:39
    3.2.把time转成字符串 s1 = 2022-02-28 19:09:39
    3.3.把time转成字符串 s1 = 20220228190939
    3.4.把time转成字符串 s1 = 2022-02
    3.5.把字符串转成time s2 = 1643905217.0
    3.6.把字符串转成time s2 = 1643905217.0
    3.7.把字符串转成time s2 = 1645978817.0
    3.8.把字符串转成time s2 = 1645977600.0
    4.1.datetime_to_date(now: datetime) = 2022-02-28
    4.2.datetime_to_time(now: datetime, back_struct_time=False) = 1646046579.0
    4.3.datetime_to_time(now: datetime, back_struct_time=True) = time.struct_time(tm_year=2022, tm_mon=2, tm_mday=28, tm_hour=19, tm_min=9, tm_sec=39, tm_wday=0, tm_yday=59, tm_isdst=-1)
    5.1.date_to_datetime(date: date) = 2022-02-28 00:00:00
    5.2.datetime_to_time(now: datetime, back_struct_time=False) = 1645977600.0
    5.3.datetime_to_time(now: datetime, back_struct_time=True) = time.struct_time(tm_year=2022, tm_mon=2, tm_mday=28, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=59, tm_isdst=-1)
    6.1.time_to_datetime(timestamp: 'float or struct_time', separator=True, **kwargs) = 2022-02-28 19:09:39
    6.2.time_to_datetime(timestamp: 'float or struct_time', separator=True, **kwargs) = 2022-02-28 19:09:39
    6.3.time_to_datetime(timestamp: 'float or struct_time', separator=False, **kwargs) = 2022-02-28 19:09:39
    6.4.time_to_datetime(timestamp: 'float or struct_time', separator=True, **kwargs) = 2022-02-28 00:00:00
    7.1.time_to_date(timestamp: 'float or struct_time')= 2022-02-28
    7.2.time_to_date(timestamp: 'float or struct_time')= 2022-02-28

    '''
def test_pd_np_python_date():
    print('test pandas numpy python date conver start...')
    now = datetime.datetime.now()
    today = now.date()
    t1 = time.time()
    t2 = time.localtime()
    print('1.1.datetime_to_timestamp(datetime)=',
          Date.datetime_to_timestamp(now))
    s = pd.Series(['2022-02-28 22:55:59', '2023-01-12 12:22:59'])
    print('1.2.datetime_to_timestamp(series) =', Date.datetime_to_timestamp(s))
    print('1.3.datetime_to_timestamp(str) =', Date.datetime_to_timestamp(s[0]))

    print('2.1.date_to_timestamp(date)=', Date.datetime_to_timestamp(today))
    print('2.2.time_to_timestamp(float) =', Date.time_to_timestamp(t1))
    print('2.3.time_to_timestamp(struct_time) =', Date.time_to_timestamp(t2))
    print(
        '2.4.str_to_timestamp(str) =',
        Date.str_to_timestamp(
            s[0],
            unit='ns'))

    # Timestamp转datetime
    ts = Date.time_to_timestamp(t1)
    print('3.1.timestamp_to_datetime(str)=', Date.timestamp_to_datetime(s[0]))
    print('3.2.timestamp_to_datetime(timestamp) =',
          Date.timestamp_to_datetime(ts))
    rng = pd.date_range(start='20210201', end='20210203', freq='D')
    print('3.3.timestamp_to_datetime(date_range) =',
          Date.timestamp_to_datetime(rng))

    # Timestamp转date
    print('3.4.timestamp_to_date(ts) =', Date.timestamp_to_date(ts))

    # Timestamp转time
    print('3.5.timestamp_to_time(ts,False) =', Date.timestamp_to_time(ts))
    print('3.6.timestamp_to_time(ts,True) =', Date.timestamp_to_time(ts, True))

    # Timestamp转str
    print('3.71.timestamp_to_str(ts) =', Date.timestamp_to_str(ts))
    print('3.72.timestamp_to_str(ts) =', Date.timestamp_to_str(ts, True))
    print(
        '3.73.timestamp_to_str(ts) =',
        Date.timestamp_to_str(
            ts,
            format='%Y%m'))

    # Timestamp转datetime64
    print('4.1.timestamp_to_datetime64(ts) =',
          Date.timestamp_to_datetime64(ts))
    print(
        '4.2.timestamp_to_datetime64(str) =',
        Date.timestamp_to_datetime64(
            s[0],
            unit='ns'))
    print(
        '4.3.str_to_datetime64(ts) =',
        Date.str_to_datetime64(
            s[0],
            unit='ns'))
    print(
        '4.4.str_to_datetime64(int) =',
        Date.str_to_datetime64(
            time.time_ns(),
            unit='ns'))

    # datetime转np.datetime64
    print('5.1.datetime_to_datetime64(datetime) =',
          Date.datetime_to_datetime64(now))
    print('5.2.datetime_to_datetime64(date) =',
          Date.datetime_to_datetime64(today))

    # date转np.datetime64
    print('5.3.date_to_datetime64(datetime) =', Date.date_to_datetime64(now))
    print('5.4.date_to_datetime64(date) =', Date.date_to_datetime64(today))

    # time转np.datetime64
    print('5.5.time_to_datetime64(ts) =', Date.time_to_datetime64(t1))
    print('5.6.time_to_datetime64(int) =', Date.time_to_datetime64(t2))

    # np.datetime64[s]转datetime.datetime
    dt64 = Date.time_to_datetime64(t1)
    print('6.1.datetime64_to_datetime(dt64) =',
          Date.datetime64_to_datetime(dt64))
    print('6.2.datetime64_to_datetime(str) =',
          Date.datetime64_to_datetime(s[0]))

    # np.datetime64[s]转datetime.date
    print('6.3.datetime64_to_date(dt64) =', Date.datetime64_to_date(dt64))
    print('6.4.datetime64_to_date(str) =', Date.datetime64_to_date(s[0]))
    # def datetime64_to_date(dt64: 'str or np.datetime64'):

    # np.datetime64[s]转time
    print('6.5.datetime64_to_time(dt64) =', Date.datetime64_to_time(dt64))
    print('6.6.datetime64_to_time(str) =', Date.datetime64_to_time(s[0], True))

    # np.datetime64[]转Timestamp
    print('6.71.datetime64_to_timestamp(str) =',
          Date.datetime64_to_timestamp(s[0]))
    print('6.72.datetime64_to_timestamp(dt64) =',
          Date.datetime64_to_timestamp(dt64))
    print(
        '6.73.datetime64_to_timestamp(dt64) =',
        Date.datetime64_to_timestamp(
            time.time_ns(),
            unit='ns'))

    print('7.datetime64_convert(str) =', Date.datetime64_convert(dt64, 'D'))

    '''
    test pandas numpy python date conver start...
    1.1.datetime_to_timestamp(datetime)= 2022-03-01 00:24:32.464204
    1.2.datetime_to_timestamp(series) = 0   2022-02-28 22:55:59
    1   2023-01-12 12:22:59
    dtype: datetime64[ns]
    1.3.datetime_to_timestamp(str) = 2022-02-28 22:55:59
    2.1.date_to_timestamp(date)= 2022-03-01 00:00:00
    2.2.time_to_timestamp(float) = 2022-03-01 00:24:32
    2.3.time_to_timestamp(struct_time) = 2022-03-01 00:24:32
    2.4.str_to_timestamp(str) = 2022-02-28 22:55:59
    3.1.timestamp_to_datetime(str)= 2022-02-28 22:55:59
    3.2.timestamp_to_datetime(timestamp) = 2022-03-01 00:24:32
    3.3.timestamp_to_datetime(date_range) = [datetime.datetime(2021, 2, 1, 0, 0) datetime.datetime(2021, 2, 2, 0, 0)
     datetime.datetime(2021, 2, 3, 0, 0)]
    3.4.timestamp_to_date(ts) = 2022-03-01
    3.5.timestamp_to_time(ts,False) = 1646065472.0
    3.6.timestamp_to_time(ts,True) = time.struct_time(tm_year=2022, tm_mon=3, tm_mday=1, tm_hour=0, tm_min=24, tm_sec=32, tm_wday=1, tm_yday=60, tm_isdst=-1)
    3.71.timestamp_to_str(ts) = 2022-03-01 00:24:32
    3.72.timestamp_to_str(ts) = 2022-03-01 00:24:32
    3.73.timestamp_to_str(ts) = 202203
    4.1.timestamp_to_datetime64(ts) = 2022-03-01T00:24:32.000000000
    4.2.timestamp_to_datetime64(str) = 2022-02-28T22:55:59.000000000
    4.3.str_to_datetime64(ts) = 2022-02-28T22:55:59.000000000
    4.4.str_to_datetime64(int) = 2022-02-28T16:24:32.472204500
    5.1.datetime_to_datetime64(datetime) = 2022-03-01T00:24:32.464204
    5.2.datetime_to_datetime64(date) = 2022-03-01
    5.3.date_to_datetime64(datetime) = 2022-03-01T00:24:32.464204
    5.4.date_to_datetime64(date) = 2022-03-01
    5.5.time_to_datetime64(ts) = 2022-03-01T00:24:32.000000
    5.6.time_to_datetime64(int) = 2022-03-01T00:24:32.000000
    6.1.datetime64_to_datetime(dt64) = 2022-03-01 00:24:32
    6.2.datetime64_to_datetime(str) = 2022-02-28 22:55:59
    6.3.datetime64_to_date(dt64) = 2022-03-01
    6.4.datetime64_to_date(str) = 2022-02-28
    6.5.datetime64_to_time(dt64) = 1646065472.0
    6.6.datetime64_to_time(str) = time.struct_time(tm_year=2022, tm_mon=2, tm_mday=28, tm_hour=22, tm_min=55, tm_sec=59, tm_wday=0, tm_yday=59, tm_isdst=-1)
    6.71.datetime64_to_timestamp(str) = 2022-02-28 22:55:59
    6.72.datetime64_to_timestamp(dt64) = 2022-03-01 00:24:32
    6.73.datetime64_to_timestamp(dt64) = 2022-02-28 16:24:32.478204900
    7.datetime64_convert(str) = 2022-03-01
    '''
if __name__ == '__main__':
    test_workdays()
    test_date()
    test_pd_np_python_date()

精彩评论(0)

0 0 举报