python - Why is my timezone datetime wrong? -
i use code format time time comes out 5 hours wrong. should 06 in calcutta , formats time 01... something. wrong code?
def datetimeformat_viewad(to_format, locale='en', timezoneinfo='asia/calcutta'): tzinfo = timezone(timezoneinfo) month = months[to_format.month - 1] input = pytz.timezone(timezoneinfo).localize( datetime(int(to_format.year), int(to_format.month), int(to_format.day), int(to_format.hour), int(to_format.minute))) date_str = '{0} {1}'.format(input.day, _(month)) time_str = format_time(input, 'h:mm', tzinfo=tzinfo, locale=locale) return "{0} {1}".format(date_str, time_str)
- update
this code worked according answer below.
def datetimeformat_viewad(to_format, locale='en', timezoneinfo='asia/calcutta'): import datetime dt import pytz utc = pytz.utc to_format = dt.datetime(int(to_format.year), int(to_format.month), int(to_format.day), int(to_format.hour), int(to_format.minute)) utc_date = utc.localize(to_format) tzone = pytz.timezone(timezoneinfo) tzone_date = utc_date.astimezone(tzone) month = months[int(tzone_date.month) - 1] time_str = format_time(tzone_date, 'h:mm') date_str = '{0} {1}'.format(tzone_date.day, _(month)) return "{0} {1}".format(date_str, time_str)
it sounds to_format
naive datetime in utc time. want convert calcutta time.
to this, localize to_format
utc time1, , use astimezone
convert timezone-aware time calcutta time:
import datetime dt import pytz utc = pytz.utc to_format = dt.datetime(2015,7,17,1,0) print(to_format) # 2015-07-17 01:00:00 utc_date = utc.localize(to_format) print(utc_date) # 2015-07-17 01:00:00+00:00 timezoneinfo = 'asia/calcutta' tzone = pytz.timezone(timezoneinfo) tzone_date = utc_date.astimezone(tzone) print(tzone_date) # 2015-07-17 06:30:00+05:30
1the tzone.localize
method not convert between timezones. interprets given localtime 1 given in tzone
. if to_format
meant interpreted utc time, use utc.localize
convert naive datetime timezone-aware utc time.
Comments
Post a Comment