tags:

views:

34

answers:

2

For python, how do i convert a DatetimeField (has my local server time) to a datetimefield in UTC zone?

+1  A: 

The best that I can come up with is to convert it to a timestamp and then use the datetime.utcfromtimestamp class method

import time
import datetime

def to_utc(d)
    ts = time.mktime(d.timetuple()) + d.microsecond
    return datetime.datetime.uctfromtimestamp(ts)
aaronasterling
@David Hsu: If an answer is accepted, it is presumably useful also. You can - and if the answer warrants - accept **and** vote it as useful.
msw
A: 

By DatetimeField, do you mean a datetime.datetime object? If so, then first note that datetime.datetime objects come in two varieties: "naïve" and "time-zone aware".

If your datetime.datetime object is time-zone aware, then you can use the astimezone method to convert between timezones: (Python does not come with timezone data. Its easiest to use the third-party pytz module to define timezones):

import pytz
import datetime

utc=pytz.utc
est=pytz.timezone('US/Eastern')

# make a time-zone aware datetime.datetime object:
now=datetime.datetime.now(est)
print(now.astimezone(utc))
# 2010-09-21 01:43:07.882858+00:00

If the datetime.datetime object is naïve, then you must use the replace method to make it time-zone aware first:

# make a naïve datetime.datetime object:
now=datetime.datetime.now()
now=now.replace(tzinfo=est)
print(now.astimezone(utc))
# 2010-09-21 02:44:47.212483+00:00
unutbu