Python 为什么pickle不使用不同的时间戳字符串保存obj文件-ctime和strftime?

Python 为什么pickle不使用不同的时间戳字符串保存obj文件-ctime和strftime?,python,pickle,Python,Pickle,我正在使用pickle保存obj文件。Obj文件用于保存模型 import numpy as np import pandas as pd import dill as pickle from sklearn.base import BaseEstimator class clf_express(BaseEstimator): """ Base class for model handling """ def __init__(self): ""

我正在使用pickle保存obj文件。Obj文件用于保存模型

import numpy as np
import pandas as pd
import dill as pickle
from sklearn.base import BaseEstimator

class clf_express(BaseEstimator):
    """
    Base class for model handling
    """
    def __init__(self):
        """
        Assign objects to use in transform() and predict() methods
        """

        #creation_time = pd.Timestamp.now().ctime()
        time = pd.Timestamp.now().strftime('%Y-%m-%d-%H-%M')
        self.name = "RISK_MODEL_for_credit_card_without_non_logical_created_at_" + time  

    def pickle_myself(self):
        """
        Save class object to binary file
        """
        self.date_create = pd.Timestamp.now().ctime()
        with open(self.name +'.obj', 'wb') as f:
            pickle.dump(self, f, protocol=3)
问题从pickle_-imf方法()开始

如果将strftime()用作时间戳,则此代码有效:

        time = pd.Timestamp.now().strftime('%Y-%m-%d-%H-%M') #this works
        self.name = "RISK_MODEL_for_credit_card_without_non_logical_created_at_" + time
    time = pd.Timestamp.now().ctime()
    self.name = "RISK_MODEL_for_credit_card_without_non_logical_created_at_" + time
当我自己调用pickle_()时,它会工作,它会将其保存并转储为obj文件。 我保存的模型的名称为:

'RISK_MODEL_for_credit_card_without_non_logical_created_at_2019-12-19-17-42'
如果使用ctime()作为时间戳,则此代码不起作用:

        time = pd.Timestamp.now().strftime('%Y-%m-%d-%H-%M') #this works
        self.name = "RISK_MODEL_for_credit_card_without_non_logical_created_at_" + time
    time = pd.Timestamp.now().ctime()
    self.name = "RISK_MODEL_for_credit_card_without_non_logical_created_at_" + time
我应该为我的模型命名为:

'RISK_MODEL_for_credit_card_without_non_logical_created_at_Thu Dec 19 17:42:44 2019'
但是strftime和ctime都是字符串!为什么腌菜堆不起作用

错误消息:

OSError: [Errno 22] Invalid argument: 'RISK_MODEL_for_credit_card_without_non_logical_created_at_Thu Dec 19 17:44:14 2019.obj'

这与pickle的库无关,如果您查看得到的错误,它会显示
OSError:[Errno 22]

若你们搜索这个错误,你们可能会偶然发现这个问题

这会让我想到一个问题:你在吗?因为你要写的文件名中有冒号

然后问题是您试图用冒号命名文件:

'RISK_MODEL_for_credit_card_without_non_logical_created_at_Thu Dec 19 17:42:44 2019'

做一个
.replace(“:”,“”)
就足以修复它了。

只要用其他东西替换冒号,例如“quo”或点“.”或任何你喜欢的东西。只需删除
。thx u,我意识到我对它的设计太过火了。为了可读性,是的,ctime更好-我想使用它是因为这个原因。@kaban如果我的答案解决了您的问题,您能通过接受它将其标记为已解决吗?谢谢
在文件系统中是无效的文件名字符。