attribute 'tzinfo' of 'datetime.datetime' objects is not writable

bobobobo picture bobobobo · Jan 18, 2010 · Viewed 37.6k times · Source

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.

Answer

Alex Martelli picture Alex Martelli · Jan 18, 2010

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)