-1

I am trying to convert UTC time to local time zone using below code. it's working fine on ubuntu 18.04. But getting an error in windows 10. Because tz.gettz() return None.

In command prompt getting below error:

astimezone() argument 1 must be datetime.tzinfo, not None.

Here is the code:

from dateutil import tz
def convert_to_localtz(self,date):
    tz1 = self._context.get('tz')// Value is 'Asia/Calcutta'
    to_zone = tz.gettz(tz1)
    print'to_zone',to_zone // Prints None
    from_zone = tz.tzutc()
    utc = date.replace(tzinfo=from_zone)
    date = utc.astimezone(to_zone)
    return date

Installed python version is 3.7

How can i resolve this?

KbiR
  • 4,047
  • 6
  • 37
  • 103
  • Can you share your import statements, and an example of _context since this is a method that starts by getting something from what appears to be a dict on a class? Also, I'm not quite sure what is happening with the print function in this snippet. It looks like it's being used as a statement when it's a function. – Alexander Jul 16 '19 at 12:03
  • @Alexander I updated my code snippet. – KbiR Jul 16 '19 at 12:09
  • did you consider using ```pytz``` and ```tzlocal``` instead of dateutil and check if the error happens there as well? According to [this post](https://stackoverflow.com/questions/16156597/how-can-i-convert-windows-timezones-to-timezones-pytz-understands) you sould be fine with those packages. – FObersteiner Jul 19 '19 at 11:11

2 Answers2

0

From docs

On Windows, the standard is extended to include the Windows-specific zone names provided by the operating system:

>>> gettz('Egypt Standard Time')
tzwin('Egypt Standard Time')

and

name – A time zone name (IANA, or, on Windows, Windows keys), ...


So I think your tz1 should be India Standard Time (at least based on https://support.microsoft.com/en-us/help/973627/microsoft-time-zone-index-values).

Dušan Maďar
  • 9,269
  • 5
  • 49
  • 64
  • Madar, Thank you for the reply. Since i am using the same code for both, how can i detect the os and convert these values? – KbiR Jul 16 '19 at 12:15
  • That's a different question. Though, https://github.com/regebro/tzlocal should help with that. – Dušan Maďar Jul 16 '19 at 12:21
  • This should be helpful too https://stackoverflow.com/questions/13218506/how-to-get-system-timezone-setting-and-pass-it-to-pytz-timezone – Dušan Maďar Jul 16 '19 at 12:27
0

Here is code that will work on *nix and Windows:

import os
import subprocess
from dateutil import tz
TZ_LOCAL = tz.gettz()
if os.name == 'nt':
    sTZ = subprocess.check_output('tzutil /g').decode('utf-8')
    TZ_LOCAL = tz.gettz(sTZ)

To be honest, I'm kind of surprised that Python does not do this automatically with tz.gettz(). You would figure that the local timezone would be a key bootstrap artifact to preload.

If I raise a ticket for this, I'll link it here for others to upvote.

Timothy C. Quinn
  • 3,739
  • 1
  • 35
  • 47