I'm trying to parse an ISO date string in Python, but so far, I'm unable to make Python to apply the parsed timezone; it seems to apply the system on each and every time, unrelated to the parser library I'm trying to use.
What am I missing here?
machine #1
$ date +'%Y-%m-%d %H:%M:%S %Z'
2016-12-12 09:33:23 CET
Linux Mint 18, python 3.5 from system package, virtualenv, set to CET as system time:
Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> t="2015-07-28T17:27:56+0000"
>>> import iso8601
>>> d = iso8601.parse_date( t )
>>> print(d)
2015-07-28 17:27:56+00:00
>>> print(d.strftime('%s'))
1438100876
>>> import pytz
>>> print(d.astimezone(pytz.utc).strftime('%s'))
1438100876
>>> tz = pytz.timezone('UTC')
>>> print( tz.localize( d ) )
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/cadeyrn/petermolnar.net/venv/lib/python3.5/site-packages/pytz/__init__.py", line 227, in localize
raise ValueError('Not naive datetime (tzinfo is already set)')
ValueError: Not naive datetime (tzinfo is already set)
>>> print(d.astimezone(tz).strftime('%s'))
1438100876
>>> import dateutil.parser
>>> d = dateutil.parser.parse( t )
>>> print( d )
2015-07-28 17:27:56+00:00
>>> print(d.strftime('%s'))
1438100876
>>> print(d.astimezone(pytz.utc).strftime('%s'))
1438100876
machine #2:
$ date +'%Y-%m-%d %H:%M:%S %Z'
2016-12-12 08:33:46 UTC
Debian 8 Jessie, python 3.5 compiled, virtualenv, set to UTC as system time:
Python 3.5.2 (default, Dec 9 2016, 16:14:46)
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> t="2015-07-28T17:27:56+0000"
>>> import iso8601
>>> d = iso8601.parse_date( t )
>>> print(d)
2015-07-28 17:27:56+00:00
>>> print(d.strftime('%s'))
1438104476
>>> import pytz
>>> print(d.astimezone(pytz.utc).strftime('%s'))
1438104476
>>> tz = pytz.timezone('UTC')
>>> print( tz.localize( d ) )
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/petermolnar.net/venv/lib/python3.5/site-packages/pytz/__init__.py", line 227, in localize
raise ValueError('Not naive datetime (tzinfo is already set)')
ValueError: Not naive datetime (tzinfo is already set)
>>> print(d.astimezone(tz).strftime('%s'))
1438104476
>>> import dateutil.parser
>>> d = dateutil.parser.parse( t )
>>> print( d )
2015-07-28 17:27:56+00:00
>>> print(d.strftime('%s'))
1438104476
>>> print(d.astimezone(pytz.utc).strftime('%s'))
1438104476
The correct one should be 1438104476
for both, and that's not what happens.