Search code examples
pythonpymysql

Convert CharField to String


For a database query with pymysql, I'm getting the model

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

Getting the date works, but I have to do some calculations with date1. For this, I need to convert it to a datetime object with datetime.strptime().

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. How can I get the content of the CharField into a string? 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.


Solution

  • This issue is that you're accessing the CharField from the class, rather than an instance of the class. Try this instead:

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