'datetime.datetime'对象的属性'tzinfo'不可写 [英] attribute 'tzinfo' of 'datetime.datetime' objects is not writable
问题描述
如何设置刚刚从数据存储区出来的datetime实例的时区?
How do I set the timezone of a datetime instance that just came out of the datastore?
首次出现时,它是UTC。我想将其改为EST。
When it first comes out it is in UTC. I want to change it to EST.
我正在尝试,例如:
class Book( db.Model ):
creationTime = db.DateTimeProperty()
当一本书被检索时,我想立即设置它的tzinfo:
When a Book is retrieved, I want to set its tzinfo immediately:
book.creationTime.tzinfo = EST
Where I use this example for my EST object
但是我得到:
attribute 'tzinfo' of 'datetime.datetime' objects is not writable
我已经看到一些建议pytz和python-dateutil的答案,但我真的想要回答这个问题。
I've seen a number of answers that recommend pytz and python-dateutil, but I really want an answer to this question.
推荐答案
datetime
的对象是不可变的,所以你永远不会改变任何属性 - 你创建一个新的对象,其中一些属性相同,还有一些不同的,并将其分配给您需要分配的任何东西。
datetime
's objects are immutable, so you never change any of their attributes -- you make a new object with some attributes the same, and some different, and assign it to whatever you need to assign it to.
在您的情况下,而不是
book.creationTime.tzinfo = EST
你必须代码
book.creationTime = book.creationTime.replace(tzinfo=EST)
这篇关于'datetime.datetime'对象的属性'tzinfo'不可写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!