1

Here is my code

>>>from datetime import datetime
>>>from dateutil import tz
>>>current_time = datetime.utcnow().replace(tzinfo=tz.gettz('Asia/Calcutta'))
>>>2013-05-12 17:11:36.362000+05:30

i don't want offset-aware i want to add time difference to my current time so the time will be

>>>2013-05-12 22:41:36.362000

so that i will be able to get time difference from by simply.

>>> datetime.utcnow() - current_time 

Thanks,

lokeshjain2008
  • 1,879
  • 1
  • 22
  • 36

2 Answers2

0

You can get the offset by using datetime.utcoffset()

current_time = datetime.utcnow().replace(tzinfo=tz.gettz('Asia/Calcutta'))
td = datetime.utcoffset(current_time)
#datetime.timedelta(0, 19800)
td.total_seconds() / 3600
#5.5
BrtH
  • 2,610
  • 16
  • 27
0

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
Community
  • 1
  • 1
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677