views:

189

answers:

3

I am working on a Django app that needs to report the local time relative to the user. I would prefer not ask the user to input the time zone directly because I have his address stored in the database. I am only considering American users. Since most states in the USA are in only one time zone it is possible to calculate the time zone based on the state information for most cases. I want to give a function the name of a state/geographic information and have it return the time offset from UTC of that state considering day light savings time.

Is there a library that can do this for python?

+3  A: 

I am not sure such a library exists. Every state in the USA doesn't have only one time zone.

Have a look here: List of U.S. states by time zone

Many states have more than one.

I guess you could still use that list and pick the timezone that the majority of the state uses and then allow the users to customize theirs if it differs.

Andre Miller
Wow, you just blew my mind. I never knew that some states had multiple time zones. For those I could prompt for user input on time zones and do it automatically for states that have only one.
hekevintran
A: 

I'm not sure how reliable it is, but the HTTP request - encapsulated in Django in the request object - has a TZ header which shows the client's time zone.

>>> request.META['TZ']
'Europe/London'
Daniel Roseman
I believe that is incorrect. The META['TZ'] field is set to your TIME_ZONE setting: http://docs.djangoproject.com/en/dev/ref/settings/#time-zone
brianz
A: 

Like Andre Miller pointed out, time zones are not tied to state. You're probably better off using the zipcode, because a few cities cross timezone lines.

There are a few databases you can purchase that that map zipcodes to time zones. Here's one I found that also includes the UTC shift and Daylight Savings:

USA 5-digit Zipcode DB with time zone info.

I haven't done the time zone thing before, but I've used this sort of database for lat/log information. The data does change, so plan on updating your database a few times a year.

BTW, if anybody knows of a free database like this, please post: I think it would be really handy for the community.

Chip Tol