I have a python application that is sending email reminders to users in different timezones. The start time is set to a given date and time, and the reminder may be set to some number of minutes before the start time.
The previous developer did not take into account the user's timezone, so reminders were always being sent based on the server's time.
Using the pytz documentation, I initially tried using UTC for everything, and while this worked in development, the reminders were still off in production. At first, I assumed that this was a problem with NTP on the server, but this was not the case.
I wanted to confirm that development and production were indeed behaving differently, so I created a simple script for testing between the two:
server_time = datetime.datetime.utcnow()
print "Server Time:", server_time
user_timezone = pytz.timezone('America/Montevideo')
print "User Timezone:", user_timezone
user_offset = user_timezone.utcoffset(server_time)
print "Offset:", user_offset
user_datetime = server_time + user_offset
print "User Time:", user_datetime
The result in development (correct):
Server Time: 2011-09-07 16:53:00.711334
User Timezone: America/Montevideo
Offset: -1 day, 21:00:00
User Time: 2011-09-07 13:53:00.71133
The result in production (incorrect):
Server Time: 2011-09-07 16:53:01.767143
User Timezone: America/Montevideo
Offset: -1 day, 20:15:00
User Time: 2011-09-07 13:08:01.767143
So it looks 开发者_如何学Clike pytz is simply giving the wrong offset. Note that it doesn't matter if I use a different timezone; every one I've tried gives the wrong offset.
As for the difference in environments, both are Ubuntu boxes, but production is running Python 2.5.2 and development is 2.6.2.
There aren't very many bugs reported for pytz, and I haven't found a reason for different offsets in any of my searching.
So is this a problem with pytz data on my production server? A pytz bug? Or a problem with my understanding of pytz? What am I missing?
Using pytz 2010 version
$ python test.py
Server Time: 2011-09-16 00:20:49.479426
User Timezone: America/Montevideo
**Offset: -1 day, 20:15:00** wrong!
User Time: 2011-09-15 20:35:49.479426-03:00
Using pytz 2011 version
$ python test.py
Server Time: 2011-09-16 00:36:54.764812
User Timezone: America/Montevideo
**Offset: -1 day, 21:00:00** great!
User Time: 2011-09-15 21:36:54.764812
Look at the pytz.VERSION and make sure you are using at least 2011h
>>> import pytz
>>> pytz.VERSION
'2011h'
If you have 2010, remove and replace:
>>> pytz.__file__
/usr/lib/python2.6/dist-packages/pytz/__init__.pyc
$ sudo rm -r /usr/lib/python2.6/dist-packages/pytz*
$ sudo pip install pytz == 2011h
精彩评论