-1

I have this function that converts a timestamp to a datetime object that says either; "Today at 10:56 pm" or "Yesterday at 1:06 am" or others...

I'm having some issues with it currently.

otherdate = 1504246379
now = time.time()
if otherdate:
    dt = now - otherdate
    offset = dt.seconds + (dt.days * 60 * 60 * 24)
if offset:
    delta_s = offset % 60
    offset /= 60
    delta_m = offset % 60
    offset /= 60
    delta_h = offset % 24
    offset /= 24
    delta_d = offset
else:
    raise ValueError("Must supply otherdate or offset (from now)")
if delta_d > 1:
    if delta_d > 6:
        date = now + timedelta(days=-delta_d, hours=-delta_h, minutes=-delta_m)
        return date.strftime('%A, %Y %B %m, %H:%I')
    else:
        wday = now + timedelta(days=-delta_d)
        return wday.strftime('%A')
if delta_d == 1:
    return "Yesterday"
if delta_h > 0:
    return "%dh%dm ago" % (delta_h, delta_m)
if delta_m > 0:
    return "%dm%ds ago" % (delta_m, delta_s)
else:
    return "%ds ago" % delta_s

The current error I receive is:

Traceback (most recent call last):
File "test.py", line 69, in <module>
date = get_long_date(timestamp)
File "test.py", line 40, in get_long_date
offset = dt.seconds + (dt.days * 60 * 60 * 24)
AttributeError: 'float' object has no attribute 'seconds'

So I went to add:

dt = timedelta(dt)

and that clears the error, however if I print the delta_d (days offset) its a negative number... Can someone help me complete my function?

Thank you,

Denis Angell

Denis Angell
  • 343
  • 1
  • 4
  • 14

2 Answers2

1

dt in your code is of type float since you are subtracting two float types.

>>> type(dt)
<type 'float'>

You may need to convert dt to

dt = timedelta(seconds=dt)

Also ,You may want to try natural library to cut down on your code.

pip install natural

Check documentation here

You can find forward or backward delta directly with one liner.

from natural import date
import time
>>> otherdate = 1504246379
>>> date.day(time.time() - otherdate)
'January 13'
>>> date.day(time.time() + otherdate)
'May 14'
>>> 

Hope it helps.

Anil_M
  • 10,893
  • 6
  • 47
  • 74
0

dt = now - otherdate will return a float, not a datetime or timedelta object, dt.day etc. will fail for that reason.

The module datetime contains the class method datetime.utcfromtimestamp(timestamp) which might well do the conversion you intend to implement. Have a look at the class library in the Python docs...

Juergen
  • 69
  • 5