[Tutor] datetime, time zones, and ISO time
David Perlman
dperlman at wisc.edu
Wed Feb 17 23:38:57 CET 2010
On Feb 17, 2010, at 4:17 PM, Sander Sweers wrote:
> On 17 February 2010 22:37, David Perlman <dperlman at wisc.edu> wrote:
>> As far as I can tell, this should always work. So wouldn't it be
>> nice if
>> there were a less convoluted way to get this??
>
> There is pytz [1] which should provide a simpler way to manage
> timezone info in python.
Well, this is actually more complicated, not simpler. The description
says:
pytz brings the Olson tz database into Python. This library allows
accurate and cross platform timezone calculations using Python 2.3 or
higher. It also solves the issue of ambiguous times at the end of
daylight savings, which you can read more about in the Python Library
Reference (datetime.tzinfo).
I don't want to deal with any of that stuff, I just want to know the
actual current offset between local time and UTC. I don't care what
the offset is in Nepal; I don't care what the offset will be come
summertime; I don't care about anything in the Olson tz database. I
just want something to tell me the current offset, right here, right
now, on my own computer.
Anyway, I already wrote a function to calculate it, so it's a done
deal. At this point I'm just really surprised that I had to...
For completeness, here's what I came up with. The format function was
necessary because Google calendar queries require the time zone to be
represented in the string like:
2010-03-01T21:00:00.000-06:00
However the isoformat() methods in python instead give something like:
2010-03-01T21:00:00.000-0600
which gives a server error if you try to send it to Google.
Unfortunately, and also bizarrely, even the strftime() doesn't provide
any way to generate the format Google demands, so I had to also write
a function to do the formatting.
def tzDeltaForm(self, tzd=None):
"""return the tzdelta in the format Google wants it, such as
-06:00"""
if not tzd: tzd=self.tzDelta()
if tzd < 0:
sign = -1
tzd = -tzd
else:
sign = 1
h = sign * tzd // 3600
m = (tzd % 3600) // 60
form = '%+03d:%02d' % (h,m)
return form
def tzDelta(self):
"""by whatever means necessary, return the current offset of the
local time from utc."""
s=time.time()
t,u=time.localtime(s),time.gmtime(s)
osec=3600*(t[3]-u[3]) + 60*(t[4]-u[4]) + (t[5]-u[5])
#return datetime.timedelta(seconds=osec)
return osec
OK, I hope that is helpful to someone else someday, because it has
been an astonishing amount of pain to accomplish something seemingly
so simple... Thanks to everyone for the input, every bit of it helped
guide me along. :)
--
-dave----------------------------------------------------------------
"Pseudo-colored pictures of a person's brain lighting up are
undoubtedly more persuasive than a pattern of squiggles produced by a
polygraph. That could be a big problem if the goal is to get to the
truth." -Dr. Steven Hyman, Harvard
More information about the Tutor
mailing list