Search code examples
pythonpytz

Time conversion using pytz isn't accurate


I am using the '2014.2' version of pytz. I am converting Asia/Kuwait timezone i.e local time to UTC time using the following process:

>>> from_date = "2014/05/06 17:07"
>>> from_date = dateutil.parser.parse(from_date)
>>> utc=timezone('UTC')
>>> from_date = from_date.replace(tzinfo=timezone('Asia/Kuwait')).astimezone(utc)
>>> from_date
datetime.datetime(2014, 5, 6, 13, 55, tzinfo=<UTC>)
>>> from_date.strftime("%b %d %Y %H:%M:%S" )
'May 06 2014 13:55:00'

The actual UTC time was May 06 2014 14:06:00 which I found in: http://www.worldtimeserver.com/current_time_in_UTC.aspx Why pytz is not exactly converting to the actual time. As you can see there is a time difference between 10-11 minutes.


Solution

  • Don't use datetime.replace() with pytz timezones. From the pytz documentation:

    Unfortunately using the tzinfo argument of the standard datetime constructors ‘’does not work’’ with pytz for many timezones.

    The reason it doesn't work is that pytz timezones include historical data and datetime is not equipped to handle these.

    Use the dedicated timezone.localize() method instead:

    >>> import dateutil.parser
    >>> from pytz import timezone
    >>> from_date = "2014/05/06 17:07"
    >>> from_date = dateutil.parser.parse(from_date)
    >>> from_date = timezone('Asia/Kuwait').localize(from_date).astimezone(timezone('UTC'))
    >>> from_date
    datetime.datetime(2014, 5, 6, 14, 7, tzinfo=<UTC>)
    >>> from_date.strftime("%b %d %Y %H:%M:%S" )
    'May 06 2014 14:07:00'
    

    The timezone.localize() method applies a timezone to a naive datetime object correctly.