Python Forum

Full Version: Writing a function to calculate time range in Unix Epoch Time
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
A program I am writing has the requirement to calculate the past 24 hours (as a time range) in unix epoch time. I would like two objects... the current time, and 24 hours before the current time, in unix epoch time.

My application would use these 2 objects as parameters in an api request to "check for updates in the past 24 hours".

If my thought pattern is correct, I would need to first calculate the current time in my time zone, subtract 1 day (24 hours) from that time, then convert both of those values to unix epoch time to be passed in the request.

So far, I was able to write a small program to determine the current time in my time zone, and print it.

I would like assistance in the best way to calculate the second time I'm looking for (24 hours prior), and then convert both of those to unix epoch time to be passed to the api.

Here is what I have so far (which I derived from the datetime docs, so not much of this was done with my own brain power):

#Class to define Eastern Standard Time
class EST5EDT(datetime.tzinfo):
    
    def utcoffset(self, dt):
        return datetime.timedelta(hours=-5) + self.dst(dt)

    def dst(self, dt):
        d = datetime.datetime(dt.year, 3, 8)        #2nd Sunday in March
        self.dston = d + datetime.timedelta(days=6-d.weekday())
        d = datetime.datetime(dt.year, 11, 1)       #1st Sunday in Nov
        self.dstoff = d + datetime.timedelta(days=6-d.weekday())
        if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
            return datetime.timedelta(hours=1)
        else:
            return datetime.timedelta(0)

    def tzname(self, dt):
        return 'EST5EDT'
    
dt = datetime.datetime.now(tz=EST5EDT())
fmt = "%Y-%m-%d %H:%M:%S %Z%z"

def setTime():
    global dt, fmt
    print('The time is now: ')
    print(dt.strftime(fmt))
Epoch time is based on UTC, so timezones don't matter.
>>> import time
>>> now = time.time()
>>> then = now - 24*60*60
>>> print(f"current epoch time {now}, 24 hours ago was {then}")
current epoch time 1594755817.479174, 24 hours ago was 1594669417.479174
awesome, thank you for that example