简体   繁体   中英

How to convert a CharField to Datetime Field in Python(Django)?

I have a CharField in my model as well as my database. I want to convert this CharField column to real datetime Django format. I have this insert query like

test.objects.create(voice=m.voice, size=m.size, start_time=get_time.get('min_time'),)

I would like to create a function to solve it, but not sure how to do it. Please help.

I think directly change the character field into datetime field is hard. Your need to do it one by one.

  1. Create a new datetime column eg start_datetime
  2. Create a script to convert the start_time from string into datetime object.
  3. Edit all code that depend on start_time
  4. Delete the start_time column

This is the example conversion from string to datetime code.

import time
for obj in Test.objects.all():
    obj.start_datetime = time.strptime(obj.start_time, "%d %b %y")
    obj.save()

You might want to read this python time library .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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