python 常用方法

点点滴滴集里

打印时间

def printTime():
    print(strftime("%Y-%m-%d %H:%M:%S", localtime()))
def time_stamp_to_str(time_stamp):
    time_array = time.localtime(float(int(time_stamp) / 1000))
    return time.strftime("%Y-%m-%d %H:%M:%S", time_array)

时间处理

def before_n_days_time_stamp_float(time_stamp, days):
    local_time = time.localtime(time_stamp / 1000)
    date_time = datetime.datetime(local_time.tm_year, local_time.tm_mon, local_time.tm_mday)
    delta = datetime.timedelta(days=days)
    date_time_delta = date_time - delta
    return time.mktime(date_time_delta.timetuple()) * 1000

def before_n_days_time_stamp_pd(time_stamp, days):
    pre_days_time_stamp = (time_stamp - datetime.timedelta(days=days))
    pre_days_time_stamp_timetuple = pre_days_time_stamp.timetuple()
    return pd.Timestamp(year=pre_days_time_stamp_timetuple.tm_year, month=pre_days_time_stamp_timetuple.tm_mon, day=pre_days_time_stamp_timetuple.tm_mday)

def after_n_days_time_stamp_pd(time_stamp, days):
    pre_days_time_stamp = (time_stamp + datetime.timedelta(days=days))
    pre_days_time_stamp_timetuple = pre_days_time_stamp.timetuple()
    return pd.Timestamp(year=pre_days_time_stamp_timetuple.tm_year, month=pre_days_time_stamp_timetuple.tm_mon, day=pre_days_time_stamp_timetuple.tm_mday)

def before_n_4hours_time_stamp_pd(time_stamp, n_4hours):
    return time_stamp - datetime.timedelta(seconds=n_4hours * 4 * 3600)

def after_n_4hours_time_stamp_pd(time_stamp, n_4hours):
    return time_stamp + datetime.timedelta(seconds=n_4hours * 4 * 3600)

pandas index处理 

def pd_data_set_time_index(self, pd_data_orgin, index_name='date_time', column_name='overall_value',datetime_format=''):
        """
        设置pd index 为时间
        :param pd_data_orgin: pandas
        :param index_name: index title 名字
        :param column_name: 列名
        :return: pandas
        """
        pd_data = pd_data_orgin.copy()
        pd_data.columns = [index_name, column_name]
        if datetime_format == '':   
            pd_data[index_name] = pd.to_datetime(pd_data[index_name])  # 将数据类型转换为日期类型
        else:
            pd_data[index_name] = pd.to_datetime(pd_data[index_name],datetime_format)  # 将数据类型转换为日期类型
        pd_data = pd_data.set_index(index_name)  # 将date设置为index
        ##解决空值问题
        pd_data = pd_data[~pd_data.index.duplicated(keep='last')]
        pd_data.fillna(method='bfill', axis=0, inplace=True)
        return pd_data

pandas线性填充

window_pd.interpolate(method='linear', limit_direction='forward', axis=0, inplace=True)
window_pd.fillna(method='bfill', axis=0, inplace=True)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值