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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With