3

There is an example located at How do I find the time difference between two datetime objects in python?

It uses

def check_time_difference(t1: datetime, t2: datetime):

as in

def check_time_difference(t1: datetime, t2: datetime):
    t1_date = datetime(
        t1.year,
        t1.month,
        t1.day,
        t1.hour,
        t1.minute,
        t1.second)

    t2_date = datetime(
        t2.year,
        t2.month,
        t2.day,
        t2.hour,
        t2.minute,
        t2.second)

    t_elapsed = t1_date - t2_date

    return t_elapsed

I'm wondering, is there a way to convert that first line so that it works with Python 2? In Python 2, I get an error that says

def check_time_difference(t1: datetime, t2: datetime):
SyntaxError: invalid syntax

It works fine in Python 3.

Kade Williams
  • 1,041
  • 2
  • 13
  • 28
  • 3
    def check_time_difference(t1, t2): – Kyle Jun 20 '18 at 19:43
  • Is your question how you can make it compatible with Python 2 without changing the code, or is your question how you can convert it to Python 2 code? If it's the former, you can't. If it's the latter, remove `: ...` – erip Jun 20 '18 at 19:44
  • 1
    The parts like "t1: datetime" are called Type Hints which are new in python3.5. – Kyle Jun 20 '18 at 19:44
  • `def check_time_difference(t1, t2): return t1-t2` .. the func is overly complicated... for python2 you simply remove the type hinting – Patrick Artner Jun 20 '18 at 19:46

2 Answers2

1

Type hints, PEP 484, are new in Python 3.5.

The code you use will work under Python 2 if you just remove them:

def check_time_difference(t1, t2):

To make it truly compatible (as in: mypy will still be able to typecheck it), add a type hint comment:

def check_time_difference(t1, t2):
    # type: (datetime, datetime) -> timedelta

As far as I can see form the mypy docs this syntax requires the return type (in this case: timedelta) to be annotated, too. In your Python 3 syntax example, it is ommitted, but it would look like:

def check_time_difference(t1: datetime, t2: datetime) -> timedelta:
L3viathan
  • 26,748
  • 2
  • 58
  • 81
0

Just remove the annotations; they don't have any impact on the functionality anyway.

def check_time_difference(t1, T2):

Note, as mentioned in the comments, the function is unnecessarily complicated - it should just return t1 - t2.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895