python 写入数据库时DateTime为NULL

axr492tv  于 2023-06-28  发布在  Python
关注(0)|答案(1)|浏览(194)

我在ftp上有一个csv文件,想把时间戳和行数(这个文件的行数)存储到数据库中。不幸的是,它的日期时间总是设置为NULL。

...
class Foo(Base):
    __tablename__ = 'Foo'
    lines = Column("lines", Integer, primary_key=True)
    timestamp_of_csv_file = Column("timestamp_of_csv_file", DateTime)

    def __init__(self, lines, timestamp):
        self.lines = lines
        self.timestamp = timestamp

remote_file = sftp.open(remote_file_name)
file_date = sftp.stat(remote_file_name).st_mtime
dt_m = datetime.fromtimestamp(file_date)
data = remote_file.read()
count_lines = data.count(b'\r\n')

session.add(Foo(dt_m, count_lines))
session.commit()

这是postgres日志中的相应条目:

postgres@my_db(0)2023-06-27 09:24:11 CEST LOG:  statement: INSERT INTO "Foo" (timestamp_of_csv_file, lines) VALUES NULL, 12329)

“init”中的断点:

-> self.timestamp = timestamp
(Pdb) timestamp
datetime.datetime(2023, 6, 26, 20, 35, 14)

我做错了什么?

gc0ot86w

gc0ot86w1#

您需要修改构造函数以将时间戳参数分配给正确的列名

class Foo(Base):
    __tablename__ = 'Foo'
    lines = Column("lines", Integer, primary_key=True)
    timestamp_of_csv_file = Column("timestamp_of_csv_file", DateTime)

    def __init__(self, lines, timestamp):
        self.lines = lines
        self.timestamp_of_csv_file = timestamp

相关问题