I have an unusual experience in working with timezones. I have to format a python datetime object to iso8601
format. In linux date --iso-8601=s
would give you the result: 2017-12-11T12:30:07+03:30
. In python I have tried using isoformat
method without setting any timezone:
>>> datetime.datetime(year=2017, month=1, day=1, hour=12, minute=44, second=25, microsecond=0).isoformat()
But it returns '2017-01-01T12:44:25'
which doesn't include time difference with UTC; I guess because it's a naive datetime object. I tried using explicit timezone:
>>> datetime.datetime(year=2017, month=1, day=1, hour=12, minute=44, second=25, microsecond=0, tzinfo=pytz.timezone('Asia/Tehran')).isoformat()
But surprisingly I got '2017-01-01T12:44:25+03:26'
which is 4 minutes behind.
I checked my machine timezone with command date +'%:z %Z'
and the output was +03:30 +0330
. Timezone names are Iran
and Asia/Tehran
regarding to commands find /usr/share/zoneinfo/* -type f -exec sh -c "diff -q /etc/localtime '{}' > /dev/null && echo {}" \
and cat /etc/timezone
respectively.
In other side, I checked result of method pytz.timezone
for Iran
and Asia/Tehran
timezone names; I got LMT+3:26:00 STD
for both situations. I can use tzoffset
with 12600 as time difference seconds, but daylight saving affects this; which I want to be independent from.
I also tried to find offset seconds:
>>> d = datetime.datetime(year=2017, month=1, day=1, hour=12, minute=44, second=25, microsecond=0, tzinfo=pytz.timezone('Asia/Tehran'))
>>> tzlocal.get_localzone().utcoffset(d)
datetime.timedelta(0, 12360)
And without timezone:
>>> d = datetime.datetime(year=2017, month=1, day=1, hour=12, minute=44, second=25, microsecond=0)
>>> tzlocal.get_localzone().utcoffset(d)
datetime.timedelta(0, 12600)
But as I mentioned, if I don't set the timezone, I can't get the time difference from isoformat
.
I have 2 questions:
- Why is it different in python timezones from standard?
- How can I handle this ISO formatting with all the criteria?