How to convert the data and time according to given UTC offset using Pytz in python & django?

StackOverflow https://stackoverflow.com/questions/10799088

سؤال

I want to convert the timestamp object(fetched from models) according to given UTC offset using Pytz. Before rendering it to the template when i prints timestamp object it does with the following format:

 2012-05-29 10:03:37

I am getting the offset with the following line:

 offset = datetime.datetime.now(pytz.timezone('Asia/Kolkata')).strftime('%z')

The above offset will give +0530 .Now i want to make the changes in timestamp object with this offset. For example :

timestamp: `2012-05-29 10:03:37`
offset:   `+0530`
after change,
timestamp: `2012-05-29 15:33:37`

What about this:

timestamp: `2012-05-29 23:03:37`
offset:   `+0530`
after change,
timestamp: `2012-05-30 4:33:37`

Look at the date it also changed according to offset. After manipulating the time it can be even in 12 hour format.

Any help will be appreciable

هل كانت مفيدة؟

المحلول

I hope this is what you're looking for:

d = datetime.now(pytz.timezone('UTC'))   # get date in UTC format - you'll be getting it from the database
local = d.astimezone('Asia/Kolkata')
print local.strftime("%Y-%m-%d %H:%M:%S %z")
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top