【问题标题】:How to convert a CharField to a DateTimeField in peewee on the fly?如何在 peewee 中即时将 CharField 转换为 DateTimeField?
【发布时间】:2018-12-19 06:06:41
【问题描述】:

我有我为 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”转换为 datetime,然后将其分配给“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”。将“whencreated”转换为日期时间,放入“whencreated_dt”,保存每一行。

问候, 斯文

【问题讨论】:

  • 你为什么要使用 getattr(o, 'whencreated') 而你可以只写“o.whencreated”?当您可以只写“o.whencreated_dt = datetime...) 时,为什么还要使用 setattr?

标签: peewee


【解决方案1】:

你的例子:

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”中的? db 怎么会知道如何调用这样的函数?

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

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

这是等效的 SQL:

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

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

【讨论】:

  • 使用不好的语言的好答案。请避免戏剧性的问题链,“到底是怎么回事”和同伴。还是给个大拇指吧。
  • 我的回答虽然有些粗鲁,但旨在让提问者思考他们的问题。以及python和sql的界限。
猜你喜欢
  • 2022-10-13
  • 2012-08-29
  • 1970-01-01
  • 2017-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-24
  • 2016-10-27
相关资源
最近更新 更多