You can obtain the offset with as a datetime.timedelta
using:
offset = current_time.utcoffset()
The offset can then be added or subtracted from the current_time to obtain the desired datetime.
import datetime as DT
import dateutil.tz as tz
import dateutil
current_time = DT.datetime.utcnow().replace(tzinfo=tz.gettz('Asia/Calcutta'))
print(current_time)
# 2013-05-12 18:33:19.368122+05:30
offset = current_time.utcoffset()
naive_time = current_time.replace(tzinfo=None)
print(naive_time)
# 2013-05-12 18:33:19.368122
print(naive_time + offset)
# 2013-05-13 00:03:19.368122
Note that if you want the UTC time, you should subtract the offset:
print(naive_time - offset)
# 2013-05-12 13:03:19.368122
A simpler way to get the UTC datetime would be to use the astimezone
method however:
utc = dateutil.tz.tzutc()
print(current_time.astimezone(utc))
# 2013-05-12 13:03:19.368122+00:00
Finally, note that using dateutil
and replace
to set the timezone does not always return the correct time. Here is how you could do it with pytz:
import pytz
calcutta = pytz.timezone('Asia/Calcutta')
utc = pytz.utc
current_time = calcutta.localize(DT.datetime.utcnow())
print(current_time)
# 2013-05-12 18:33:19.368705+05:30
print(current_time.astimezone(utc))
# 2013-05-12 13:03:19.368705+00:00