如何动态将PeField中的CharField转换为DateTimeField?

时间:2018-12-06 19:56:50

标签: peewee

我有为Peewee动态创建的模型。像这样:

class TestTable(PeeweeBaseModel):
    whencreated_dt = DateTimeField(null=True)
    whenchanged = CharField(max_length=50, null=True)

我使用peewee将数据从文本文件加载到表中,“ whenchanged”列包含所有日期,其格式为'%Y-%m-%d%H:%M:%S'作为varchar列。现在,我想将文本字段“ whenchanged”转换为“ whencreated_dt”中的日期时间格式。 我尝试了几件事...最后得到了这个:

# Initialize table to TestTable
to_execute = "table.update({table.%s : datetime.strptime(table.%s, '%%Y-%%m-%%d %%H:%%M:%%S')}).execute()" % ('whencreated_dt', 'whencreated')

失败,并显示“ TypeError:strptime()参数1必须为str,而不是CharField”:我试图将“ whencreated”转换为日期时间,然后将其分配给“ whencreated_dt”。

我尝试了一种变化...例如工作顺利:

# Initialize table to TestTable
to_execute = "table.update({table.%s : datetime.now()}).execute()" % (self.name)
exec(to_execute)

但这当然只是当前日期时间,而不是其他字段。

有人知道解决方案吗?

编辑...我最终确实找到了解决方法...但是我仍在寻找更好的解决方案...解决方法:

all_objects = table.select()
for o in all_objects:
    datetime_str = getattr( o, 'whencreated' )
    setattr(o, 'whencreated_dt', datetime.strptime(datetime_str, '%Y-%m-%d %H:%M:%S'))
    o.save()

遍历表中的所有行,获取“创建时”。将“创建时间”转换为日期时间,将其放入“ whencreated_dt”,然后保存每一行。

关于, 斯文

1 个答案:

答案 0 :(得分:0)

您的示例:

to_execute = "table.update({table.%s : datetime.strptime(table.%s, '%%Y-%%m-%%d %%H:%%M:%%S')}).execute()" % ('whencreated_dt', 'whencreated')

将无法正常工作。为什么?因为datetime.strptime是Python函数,并且在Python中运行。 UPDATE查询在数据库范围内有效。数据库将如何神奇地将行值传递到“ datetime.strptime”?数据库怎么会知道如何调用这样的函数?

您需要使用SQL函数-由数据库执行的函数。例如,Postgres:

TestTable.update(whencreated_dt=whenchanged.cast('timestamp')).execute()

这是等效的SQL:

UPDATE test_table SET whencreated_dt = CAST(whenchanged AS timestamp);

这应该使用正确的数据类型为您填充列。对于其他数据库,请查阅其手册。请注意,SQLite not 没有专用的日期/时间数据类型,并且datetime功能使用Y-m-d H:M:S格式的字符串。

相关问题