属性“tzinfo” “日期时间.日期时间”的对象不可写
如何设置刚刚从数据存储中出来的日期时间实例的时区?
当它第一次出现时,它是 UTC。我想把它改成EST。
例如,我正在尝试:
class Book( db.Model ):
creationTime = db.DateTimeProperty()
当检索一本书时,我想立即设置其tzinfo:
book.creationTime.tzinfo = EST
其中 我使用这个示例作为我的 EST 对象
但是我得到:
attribute 'tzinfo' of 'datetime.datetime' objects is not writable
我已经看到了许多推荐 pytz 和 python-dateutil 的答案,但我真的想要这个问题的答案。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
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.I.e., in your case, instead of
you have to code
如果您收到的日期时间为美国东部时间 (EST),但未设置 tzinfo 字段,请使用 dt.replace(tzinfo=tz) 分配 tzinfo,无需修改时间。 (您的数据库应该为您执行此操作。)
如果您收到的是 UDT 格式的日期时间,并且您希望它采用 EST 格式,那么您需要 astimezone。 http://docs.python.org/library/datetime.html#datetime .datetime.astimezone
在绝大多数情况下,您的数据库应该在 UDT 中存储和返回数据,并且您不需要使用替换(除非可能分配 UDT tzinfo)。
If you're receiving a datetime that's in EST, but doesn't have its tzinfo field set, use
dt.replace(tzinfo=tz)
to assign a tzinfo without modifying the time. (Your database should be doing this for you.)If you're receiving a datetime that's in UDT, and you want it in EST, then you need astimezone. http://docs.python.org/library/datetime.html#datetime.datetime.astimezone
In the vast majority of cases, your database should be storing and returning data in UDT, and you shouldn't need to use replace (except possibly to assign a UDT tzinfo).
您想要的就在文档中。
输出:
What you want is right there in the docs.
output: