Joe
Joe

Reputation: 4633

django, datetime and timezones

I am using: datetime.now() to get the current time in an Event app that lets you create an event that has an end date, then all of the events are displayed in a calendar and if an event is passed due it is displayed in red.

My issue is that I have some users in different timezones than me saying that the events are ending at the wrong time. They should end at midnight on the day they are due.

I have the timezone setup in my django settings.py. When I use: datetime.now() is that going off of the users local timezone or is it going off of what timezone I have setup in django?

What I want is to find midnight for the users current timezone, so if my method above is wrong, how do I go about doing that?

Thanks

Upvotes: 4

Views: 4548

Answers (3)

dannyroa
dannyroa

Reputation: 5571

Try storing the UTC Datetime instead then make the necessary adjustments based on the user's timezone:

import datetime

def getUtcNow():
    return datetime.datetime(*time.gmtime()[:6])

Upvotes: 0

John Keyes
John Keyes

Reputation: 5604

You will need your users to specify their timezone in their user profile. This can then be used to calculate local times correctly.

Check out Relativity of time – shortcomings in Python datetime, and workaround for some good information (and concrete examples).

UPDATE: From Django 1.4 it comes up with timezone support. Check it out.

Upvotes: 4

FernandoEscher
FernandoEscher

Reputation: 2990

I worked on a library to work with user timezones transparently. You should just use a Field and some timezone utils and you should get everything converted to the user timezone everytime you do a request or a query.

The library is named django-timezones, and is a modification of the one that Brosner first made.

Give it a try to see if it works for you.

Upvotes: 0

Related Questions