简体   繁体   English

将 CharField 转换为字符串

[英]Convert CharField to String

For a database query with pymysql, I'm getting the model对于使用 pymysql 的数据库查询,我得到 model

class MyModel(Model):
    id = AutoField()
    date1 = CharField()
    confirmed = IntegerField()

Getting the date works, but I have to do some calculations with date1.获取日期有效,但我必须对 date1 进行一些计算。 For this, I need to convert it to a datetime object with datetime.strptime().为此,我需要使用 datetime.strptime() 将其转换为日期时间 object。

for model in MyModel.select().where(MyModel.confirmed == 0):
    rd = MyModel.date1
    date_time_obj = datetime.strptime(rd, '%d.%m.%Y')

The problem is that date1 is a CharField, not a string, so strptime does not work.问题是 date1 是一个 CharField,而不是一个字符串,所以 strptime 不起作用。 How can I get the content of the CharField into a string?如何将 CharField 的内容转换成字符串? As the rest of the script works the way it is, ideally it would be in a way that doesn't change the retrieved data.由于脚本的 rest 按原样工作,理想情况下它不会更改检索到的数据。

This issue is that you're accessing the CharField from the class, rather than an instance of the class. Try this instead:这个问题是您从 class 访问 CharField,而不是 class 的实例。试试这个:

for model in MyModel.select().where(MyModel.confirmed == 0):
    rd = model.date1
    date_time_obj = datetime.strptime(rd, '%d.%m.%Y')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM