Converting from local -> UTC

Keith Hughitt keith.hughitt at gmail.com
Mon Jul 14 17:06:30 CEST 2008


On Jul 12, 12:52 am, "Gabriel Genellina" <gagsl-... at yahoo.com.ar>
wrote:
> En Fri, 11 Jul 2008 15:42:37 -0300, Keith Hughitt  
> <keith.hugh... at gmail.com> escribi�:
>
> > I am having a little trouble figuring out how to convert a python
> > datetime to UTC. I have a UTC date (e.g. 2008-07-11 00:00:00). I would
> > like to create a UTC date so that when I send it to MySQL (which
> > treats all dates at local dates by default), it will already have
> > incorporated the proper UTC offset. I've tried looking through the
> > docshttp://python.active-venture.com/lib/datetime-datetime.html), but
> > have not had any luck.
>
> You have to use a "timezone aware" datetime object. If all you want is to  
> store an UTC date, the tzinfo demo classes that you can find in the Python  
> docs at <http://docs.python.org/lib/datetime-tzinfo.html> may be enough.
> A more complete implementation is at <http://pytz.sourceforge.net/>
>
> If you pass a "timezone aware" datetime object as a SQL parameter, the  
> database should store it correctly (but I don't have a MySQL instance at  
> hand to test it)
>
> --
> Gabriel Genellina

Thanks for advice Gabriel. I downloaded the tzinfo demo class, saved
it as
UTC.py and imported it. I'm still not exactly sure how to use it
though. It looks like
the file already creates an instance of the UTC tzinfo class (line 20:
"utc = UTC()"),
however, when I try to test it out in the interpreter, it cannot be
found. I'm new
to python, and there is probably something obvious I'm missing, but do
you have any ideas?
Here is what I'm attempting:

============ output begin =============

Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime, UTC
>>> t = datetime.datetime(2008, 7, 14, 00, 00, 00, UTC())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable
>>> utc
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'utc' is not defined

>>> utc = UTC()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable
>>>

============ output begin =============

Any ideas?

Thanks,
Keith



More information about the Python-list mailing list