Tuesday, May 11, 2010

get the correct datetime value for python datetime module

UPDATE: Turn out that i did it in django shell, which, set the time to chicago, which make the time wrong in my system, the information here is right, except on the datetime.now() error. in normal python shell, or apps, datetime.now() should show the correct datetime. but on django, we need to setup the  timezone

So I have to use datetime in this project. the more I use it I realized that it can bite, unless used properly.

Let start with a simple example, start with
from datetime import datetime

from the doc, datetime.now() show today date and time.
the time i tested the line is 12:47 on 12 may 2010.
>>> datetime.now()
datetime.datetime(2010, 5, 11, 23, 46, 50, 383091)

Notice that the day and the date, is wrong. you should try it to see it yourself. Not wrong but unexpected

Run
>>> datetime.utcnow()
datetime.datetime(2010, 5, 12, 4, 56, 13, 315120)

better, but in utc time. That is in 12:56 pm on 12 may 2010

The way to solve it is to implement tzinfo class, which I didn't do, or we can use pytz
Which does it for us anyway. Run the following in the shell

import pytz
mytz = pytz.timezone('Asia/Kuala_Lumpur')
datetime.now(mytz)

after setting up the timezone with the right tzinfo. datetime.now() should show the correct datetime.

Note to self, python datetime can bite us,

1 comment:

  1. It's correct behavior to always store in UTC. You then use timezone to display(view) it according to the local time zone as you showed with pytz. Timezone time is relative and can even change due to legislation for daylight savings as an example.

    For the same reason, it's best to set your computer system clock to UTC, and then use timezone to translate it to the correct local time. So when you go to different countries, the internal time doesn't change (UTC), just the timezone.

    ReplyDelete