1

I am not sure I worded that correctly but python and time always confuses me. This is what I am trying. Given a unix timestamp (INT) which is definitely in the past (can be seconds ago or years ago) I want to generate a babel format_timedelta

My problem is

  1. Babel format_timedelta takes timedelta as first argument
  2. so I guess I need to generate a timedelta using time.time() (now) and the unix timestamp I have.

I can't figure out the part 2 and I believe there must be an easier/correct way to do this. Please share the best possible way to do this, also I need it to be fast in calculating since I have to use it in a web page.

def format_starttime(value, granularity="day"):
 delta = datetime.timedelta(seconds=time.time() - value)
 return format_timedelta(delta, granularity)

gives error in date.format_timedelta() AttributeError: 'module' object has no attribute 'format_timedelta'

desertnaut
  • 57,590
  • 26
  • 140
  • 166
Abhishek Dujari
  • 2,343
  • 33
  • 43

2 Answers2

2
import datetime

td = datetime.timedelta(seconds=time.time()-a_unix_timestamp)
Amber
  • 507,862
  • 82
  • 626
  • 550
  • thanks I didn't know this about timedelta that I can simply put seconds of unix time and make it timedelta object. – Abhishek Dujari Mar 29 '12 at 06:37
  • I tried with your method. but I think I has error :/ (edit and added code) – Abhishek Dujari Mar 29 '12 at 06:58
  • I think that the error you're getting has nothing to do with the code that you've shown, because the error is dealing with somewhere that you're doing `.format_timedelta` which doesn't show up anywhere in your shown code. – Amber Mar 29 '12 at 17:28
  • yes I have reached the same conclusion sadly. And both of your answers are correct to what i asked. – Abhishek Dujari Mar 29 '12 at 17:49
2

Difference between two datetime instances is a timedelta instance.

from datetime import datetime
from babel.dates import format_timedelta
delta = datetime.now() - datetime.fromtimestamp(your_timestamp)
print format_timedelta(delta, locale='en_US')

See datetime module documentation for details and more examples.

vartec
  • 131,205
  • 36
  • 218
  • 244
  • yes I have tried both answers and get the same problem. I must point out that I am using Flask and flask ext babel. It just complains of the same problem. – Abhishek Dujari Mar 29 '12 at 14:43