attribute 'tzinfo' of 'datetime.datetime' objects is not writable
Solution 1
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
book.creationTime.tzinfo = EST
you have to code
book.creationTime = book.creationTime.replace(tzinfo=EST)
Solution 2
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).
bobobobo
Updated on January 19, 2020Comments
-
bobobobo over 4 years
How do I set the timezone of a datetime instance that just came out of the datastore?
When it first comes out it is in UTC. I want to change it to EST.
I'm trying, for example:
class Book( db.Model ): creationTime = db.DateTimeProperty()
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
However I get:
attribute 'tzinfo' of 'datetime.datetime' objects is not writable
I've seen a number of answers that recommend pytz and python-dateutil, but I really want an answer to this question.
-
Auspex about 11 yearsThat's hardly very informative. You could have explained just as much by saying to use datetime.replace(tzinfo=...) - but you haven't explained how he's supposed to GET the tzinfo he wants, you've simply hardcoded an EST/EDT timezone.
-
jfs over 9 yearsnote: it doesn't convert from UTC to EST timezone ("it first comes out it is in UTC. I want to change it to EST."). The time stays the same. To convert,
book.creationTime.astimezone(EST)
could be used.