简体   繁体   中英

Python timestamp to time since conversion

I have a database column the holds timestamps in UNIX format, I am looking for a way to compare those timestamps to a timestamp from the time right now and print how many seconds/hours/days since the original timestamp.

Just to confirm I am NOT looking for a conversion from 1489757456 to 03/17/2017 @ 1:30pm . I AM looking for a conversion from 1489757456 to 1m ago/2hr ago/3d ago ect.

datetime.datetime.fromtimestamp() 

to convert your unix timestamp to a datetitme

datetime.datetime.now() 

to get the current datetime

dateutil.relativedelta.relativedelta(dt1, dt2, ...) 

to get the difference with respect to leap years.

References :

Function, like this will generate output for hours, mins and seconds from seconds number.

def secondsToHms(d):
    d = int(d);
    h = math.floor(d / 3600)
    m = math.floor(d % 3600 / 60)
    s = math.floor(d % 3600 % 60)

    htext = " hour, " if h == 1 else " hours, "
    hDisplay = str(h) + htext if h > 0 else ""
    mtext = " minute, " if m == 1 else " minutes, "
    mDisplay = str(m) + mtext if  m > 0 else ""
    stext = " second" if s == 1 else " seconds"
    sDisplay = str(s) + stext if s > 0 else ""
    return hDisplay + mDisplay + sDisplay; 

For example:

secondsToHms(344334)
>> 95.0 hours, 38.0 minutes, 54.0 seconds

So you can add your preferred formatting and also add days/months if needed in similar fashion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM