0

I have a python script running on python 3.6.4 locally buy trying to run it on a system with python 2.7.

File "report_scheduler.py", line 5, in <module>
from datetime import datetime, timedelta, timezone, tzinfo
ImportError: cannot import name timezone

I cant seem to import timezone module. I can't seem to install the timezone module. is there an easy way to import that module or modify the scripts to not need it? my only two references to that module are below.

from datetime import datetime, timedelta, timezone, tzinfo

last_run=(row[4]).replace(tzinfo=timezone.utc)
time_since_last_request = datetime.now(timezone.utc) - last_run
personalt
  • 810
  • 3
  • 13
  • 26
  • First, you're not importing a `timezone` module, you're importing the `timezone` class out of the `datetime` module. So, trying to install a `timezone` module, even if there were such a thing, wouldn't help anything – abarnert Aug 18 '18 at 23:36

2 Answers2

1

1) for the reason: as outlined e.g. in this answer datetime.now(timezone.utc) works only from Python 3.2 and later versions

2) for fixing: I would use a quick snippet like the following [check this other answer as reference]:

import pytz  # 3rd party: $ pip install pytz
from datetime import datetime

u = datetime.utcnow()
u = u.replace(tzinfo=pytz.utc) #NOTE: it works only with a fixed utc offset

# print(u)   # prints UTC time
# print(u.astimezone(pytz.timezone("America/New_York")))     # prints another timezone
Antonino
  • 3,178
  • 3
  • 24
  • 39
1

First, you're not importing a timezone module, you're importing the timezone class out of the datetime module. So, trying to install a timezone module, even if there were such a thing, wouldn't help anything.

Meanwhile, as the docs say, the timezone class was added in Python 3.2, so you don't have it in 2.7.

There used to be a backport of the datetime module from around Python 3.4 to 2.7, which would have solved your problem, but it seems to have been abandoned years ago.


So, that leaves modifying your code so that it doesn't need timezone.

Fortunately, the only instance of timezone you're ever using is the UTC one, and that's pretty easy to work around.

A timezone class is just a pre-built implementation of a tzinfo class. In 2.x, you have to implement your own tzinfo class. But the trivial class UTC example in the docs happens to be exactly what you want:

ZERO = timedelta(0)
HOUR = timedelta(hours=1)

class UTC(tzinfo):
    """UTC"""

    def utcoffset(self, dt):
        return ZERO

    def tzname(self, dt):
        return "UTC"

    def dst(self, dt):
        return ZERO

utc = UTC()

Now, everywhere you used timezone.utc, just use utc instead, and you're done.

abarnert
  • 354,177
  • 51
  • 601
  • 671