0

Hi I am trying to compare the last seen time of a user to now using flask-moment. Here is the logic:

user.last_seen = 3 mins ago #I already know how to get this using flask-moment

time_now = 5:00 pm

My goal is to do this:

{% if (time_now - user.last_seen) <= 5 mins %}
...do something...
{% else %}
...do other thing ....
{% endif %}

Both times are variable. I am able to get the two times but I don't know how to compare them like I did above. Your help will be much appreciated.

aharding378
  • 207
  • 1
  • 3
  • 16
  • You can do calculations either in Moment or in Python (both support this) but I think the module may be confusing you. If `time_now` and `user.last_seen` are both `datetime` objects in Python then your code above will work and you'll get a `timedelta` object. – Cfreak Nov 02 '17 at 02:52
  • @Cfreak can you please show me how you would do it in python? – aharding378 Nov 02 '17 at 03:01

2 Answers2

1

You can calculate another datetime object based on the last seen value you get and do the following. This is just the an example. You can do the conversion from hours to minutes, seconds and you can do timedelta(minutes=1) or timedelta(microseconds=1) too

    from datetime import datetime, timedelta
    time_now=datetime.now()
    last_seen_time=datetime.now()-timedelta(hours=3)
    print(time_now-last_seen_time)

you can use this to convert the result which is a timedelta object to minutes, seconds etc How to convert datetime.timedelta to minutes, hours in Python?

kar
  • 198
  • 1
  • 8
1

Like @Cfreak suggested, if time_now and user.last_seen are both datetime objects in Python, you can calculate the timedelta between these two datetime, then cal the function total_seconds and convert the timedelta to minutes, so that you can compare to 5 mins. like this:

import datetime
last_seen= datetime.datetime(2017, 11, 2, 11, 15, 17, 748000)
time_now = datetime.datetime.now()
time_delta_seconds = (time_now -last_seen).total_seconds() #get timedelta and calculate total seconds
time_delta_minutes = time_delta_seconds/60 # convert to minutes 4.808866666666666

Then you can compare if time_delta_minutes is less than 5 mins or not

Tiny.D
  • 6,466
  • 2
  • 15
  • 20