carte blanche
carte blanche

Reputation: 11476

[Age in days]how to convert posix time to datetime and subtract from current time to get the age?

I am trying to convert posix time to datetime to subtract from current time to get the age in days and running into below error?any guidance on how to achieve this?

import time
from datetime import datetime
from datetime import date

gerrit_last_updated_time = date.fromtimestamp(1551045234)
current_time = datetime.now()

print gerrit_last_updated_time
print current_time

age =  current_time - gerrit_last_updated_time

Error:-

Traceback (most recent call last):
  File "convert_epochtime_time.py", line 11, in <module>
    age =  current_time - gerrit_last_updated_time
TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'datetime.date'

Upvotes: 0

Views: 74

Answers (1)

benvc
benvc

Reputation: 15120

You are trying to compare a date object with a datetime object, and datetime.fromtimestamp takes seconds, so you will also need to divide by 1000 to convert milliseconds. For example:

from datetime import datetime

ts = datetime.fromtimestamp(1551045234 / 1000)
now = datetime.now()
age_in_days =  now - ts

Upvotes: 1

Related Questions