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

why is pickle not saving the obj file with different timestamp strings - ctime and strftime?

我正在使用 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_myself method()。

如果我使用 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

并且当我调用 pickle_myself() 它起作用时,它确实将其保存并转储为 obj 文件。 我保存的模型名称是:

'RISK_MODEL_for_credit_card_without_non_logical_created_at_2019-12-19-17-42'

如果我使用 ctime() 作为时间戳,此代码将不起作用:

    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]

如果你 google 这个错误,你可能会偶然发现 this 问题。

这会导致我问这个问题:你在 Windows 吗?因为您要写入的文件的名称中包含冒号。

那么问题是你试图用冒号命名你的文件:

'RISK_MODEL_for_credit_card_without_non_logical_created_at_Thu Dec 19 17:42:44 2019'

做一个 .replace(":", "_") 应该足以修复它。