pythonepochtimedelta

Unix timestamp +1 hour replacement


I defined two helper methods in Python for setting start-time and end-time and want it converted into unix timestamp (epoch):

def set_epoch_start():
    unix_epoch = datetime.utcfromtimestamp(0).replace(tzinfo=timezone.utc)
    now = datetime.now(tz=timezone.utc)
    new_time = now.replace(hour=17, minute=0, second=0, microsecond=0)
    seconds = (new_time - unix_epoch).total_seconds()
    return int(seconds)


def set_epoch_end():
    unix_epoch = datetime.utcfromtimestamp(0).replace(tzinfo=timezone.utc)
    now = datetime.now(tz=timezone.utc)
    new_time = now.replace(hour=23, minute=0, second=0, microsecond=0)
    seconds = (new_time - unix_epoch).total_seconds()
    return int(seconds)

As of now, I have hard-coded the values for hours (17 and 23), but I want the replace method for start-time to add +1 hour and the replace method for end-time to add 2 hours.

Searching for help on this I came across timedelta i.e. timedelta(hours=2), but how can I add timedelta into my two functions above?


Solution

  • First refactor your code to eliminate (the two functions are very similar). Then you need to pass in now to have a stable reference:

    from datetime import *
    
    def epoch_offset(now, delta):
        unix_epoch = datetime.utcfromtimestamp(0).replace(tzinfo=timezone.utc)
        return int((now + delta - unix_epoch).total_seconds())
    
    now = datetime.now(timezone.utc)
    for offset in (1,2):
        print(epoch_offset(now, timedelta(hours=offset)))
    

    and example output:

    1724306428
    1724302828
    

    Instead of doing the epoch calculation consider just using the timestamp() method:

    def epoch_offset(now, delta):
            return int((now + delta).timestamp())