views:

154

answers:

3

I have a python datetime object which I would like to convert to UTC. I am planning to output it in RFC 2822 format to put in an HTTP header, but I am not sure if that matters for this question. I found some information on this site about converting time objects, and it looks simpler that way, but this time I really want to use datetime objects, because I am using timedeltas to adjust them:

I tried something like this:

from datetime import datetime, timedelta

now = datetime.now()
fiveMinutesLater = datetime.now() + timedelta(minutes=5)
fiveMinutesLaterUtc = ???

Nothing in the time or datetime module looks like it would help me. It seems like I may be able to do it by passing the datetime object through 3 or 4 functions, but I am wondering if there is a simpler way.

I would prefer not to use third-party modules, but I may if it is the only reasonable choice.

+1  A: 

You can use the formatdate method in the email.Utils module like follows

>>> from email.Utils import formatdate
>>> print formatdate()
Sun, 25 Jul 2010 04:02:52 -0000

The above is date time in RFC 2822 format. By default it returns UTC time but in-case you need local time you can call formatdate(localtime=True).

For more information do check http://docs.python.org/library/email.mime.html#module-email.util

GeekTantra
+2  A: 

First you need to make sure the datetime is a timezone-aware object by setting its tzinfo member:

http://docs.python.org/library/datetime.html#datetime.tzinfo

You can then use the .astimezone() function to convert it:

http://docs.python.org/library/datetime.html#datetime.datetime.astimezone

Amber
According to the docs, I need to come up with a subclass of the tzinfo class to come up with an object that I can pass to the "now" function to make it aware of my server's time zone. That seems kind of complicated. Does anyone know a simpler way? If I find a simpler way, I will post it here.
mikez302
@mikez302 - Look into the pytz module. It is effectively a database of datetime.tzinfo timezone definitions for all common timezones.
Joe Kington
+1  A: 

I found a way to take the current time, add a timedelta object to it, convert the result to UTC, and output it in RFC 2822:

time.strftime("%a, %d-%b-%Y %H:%M:%S GMT",
    time.gmtime(time.time() + datetime.timedelta(minutes=5).seconds))

This did not exactly answer my question, but I am putting it here because it may help someone else in my situation.

EDIT: I would like to add that this trick only works if the timedelta is less than one day. If you want something that works with any sort of timedelta value, you can use timedelta.total_seconds() (for Python 2.7 and later), or with 86400*timedelta.days + timedelta.seconds. I haven't actually tried this so I'm not 100% sure if it will work.

mikez302