简体   繁体   English

如何在Python(Django)中将CharField转换为Datetime字段?

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

I have a CharField in my model as well as my database. 我的模型和数据库中都有一个CharField。 I want to convert this CharField column to real datetime Django format. 我想将此CharField列转换为真实的日期时间Django格式。 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 创建一个新的datetime列,例如start_datetime
  2. Create a script to convert the start_time from string into datetime object. 创建一个脚本,将start_time从字符串转换为datetime对象。
  3. Edit all code that depend on start_time 编辑所有依赖于start_time代码
  4. Delete the start_time column 删除start_time

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 . 您可能需要阅读此python 时间库

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

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