[以天为单位]如何将posix时间转换为日期时间并从当前时间中减去以获取年龄?

时间:2019-03-04 21:08:10

标签: python datetime

我正在尝试将posix时间转换为日期时间,以从当前时间中减去,以获取以天为单位的年龄并遇到以下错误?如何实现此目标的任何指导?

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

错误:-

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'

1 个答案:

答案 0 :(得分:1)

您正在尝试将date对象与datetime对象进行比较,而datetime.fromtimestamp需要几秒钟,因此您还需要除以1000来转换毫秒。例如:

from datetime import datetime

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