Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

python - Django DateTimeField和datetime.datetime.now()提供不同的时间(Django DateTimeField and datetime.datetime.now() giving different times)

I have a model where I want the name field to be a string representation of the timestamp, and another field to be the actual time stamp.

(我有一个模型,我希望name字段是时间戳的字符串表示形式,另一个字段是实际时间戳。)

Here is my model code:

(这是我的模型代码:)

from django.db import models
from datetime import datetime

class Image(models.Model):
    name = models.CharField(max_length=255, default=datetime.now().strftime("%Y%m%d-%H%M%S"))
    create_date = models.DateTimeField(auto_now_add=True)
    image = models.ImageField(upload_to="images/")

Then I go in the django shell and enter this:

(然后进入django shell,输入以下内容:)

>>> import models
>>> models.Image(image='images/rock.png').save()

This works but the only problem is the two times do not align.

(这可行,但是唯一的问题是两次不对齐。)

For example, I get name = 20191201-143119 and create_date = 2019-12-01 14:32:11.445474 .

(例如,我得到name = 20191201-143119create_date = 2019-12-01 14:32:11.445474 。)

How can I get these two datetimes to be the same?

(如何使这两个日期时间相同?)

  ask by dwvldg translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I've linked an answer will help you understand what is happening.

(我已经链接了一个答案,它将帮助您了解正在发生的事情。)

Achieving what you want is quite simple though.

(不过,实现您想要的东西非常简单。)

models.py

(models.py)

from django.db import models
from datetime import datetime

class Image(models.Model):
    name = models.CharField(max_length=255)
    create_date = models.DateTimeField(auto_now_add=True)
    image = models.ImageField(upload_to="images/")

    def save(self, *args, **kwargs):
        if not self.name: 
            self.name = datetime.now().strftime("%Y%m%d-%H%M%S")
        super(Image, self).save(*args, **kwargs) 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...