Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert epoch/unix time into readable format

Tags:

python

time

In python if I where do to

import time
print(time.time()+40)

It would give epoch/unix time 40 seconds from now but, how would I make it like this

import time
def difference(x):
    Time = time.time()+x
    difference = Time-time.time()
    return difference

Now, I that works great until you get higher numbers than just 60 seconds(one minute) and on a large scale like a year that can get very confusing, is there a method to have it turn it into minutes or hours,days,years in a simple method so it can return something like this?

return "That time is %s years from now %s days %s hours %s minutes and %s seconds from now"

I could think of a way to do it, but I'm afraid the way i'm doing it will result in a very large code using alot of if/else's and divmods. Thanks in advance.

like image 966
ruler Avatar asked Jul 11 '26 09:07

ruler


1 Answers

This is almost exactly the same place I stopped using time and started using datetime.

from datetime import tzinfo, timedelta, datetime
now = datetime.utcnow()
later = now - timedelta(seconds=40)


>>> now
datetime.datetime(2013, 10, 7, 15, 9, 5, 903000)
>>> print now
2013-10-07 15:09:05.903000
>>> print later
2013-10-07 15:08:25.903000

So now you can just subtract for the difference.

now = datetime.utcnow()
later = now + timedelta(weeks=78, minutes=85, seconds=128)
diff = later - now

Unfortunately datetime doesn't translate days into months/years. I assume this is because it would have to figure in leapyears and which months were between the two dates.

>>> print diff
546 days, 1:27:08




extra info:

If you start getting into other timezones, it gets a little more complicated as you need to provide a timezone object. Here is a simple version:

################################################################################
#Class definition for EST timezone since python doesn't have one
class EST(tzinfo):
    def utcoffset(self, dt):
        return timedelta(-5)

    def tzname(self, dt):
        return "EST"

    def dst(self, dt):
        return timedelta(0)

################################################################################
#Class definition for CST timezone since python doesn't have one
class CST(tzinfo):
    def utcoffset(self, dt):
        return timedelta(hours=-6)

    def tzname(self, dt):
        return "CST"

    def dst(self, dt):
        return timedelta(0)


nowcst = datetime.now(tz=CST())
nowest = now.replace(tzinfo(EST())

Using timezones really should take daylight savings into account.
*example code can be found in the python docs - http://docs.python.org/2/library/datetime.html#tzinfo-objects

like image 190
Marcel Wilson Avatar answered Jul 13 '26 22:07

Marcel Wilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!