Search code examples
pythonepoch

truncate epoch time to start of hour / day


I want to truncate epoch time (in milliseconds) to start of hour or start of day. I have created below functions and they are working fine. I am doing 3 steps process right now - convert input_epoch to datetime -> truncate datetime -> convert datetime back to epoch_time. Is there any way to directly truncate epoch time (without converting it to datetime object)? Any suggestions?

from datetime import datetime

def to_epoch_millis(dt):
    return int((dt - datetime.utcfromtimestamp(0)).total_seconds() * 1000.0)

def truncate_to_hour(dt):
    return dt.replace(microsecond=0, second=0, minute=0)

def truncate_to_day(dt):
    return dt.replace(microsecond=0, second=0, minute=0, hour=0)


# input - 1647548963623 - Thu Mar 17 2022 20:29:23
input_epoch = 1647548963623
print(to_epoch_millis(
    truncate_to_day(datetime.utcfromtimestamp(input_epoch / 1000))))  # 1647475200000 - Thu Mar 17 2022 00:00:00
print(to_epoch_millis(
    truncate_to_hour(datetime.utcfromtimestamp(input_epoch / 1000))))  # 1647547200000 - Thu Mar 17 2022 20:00:00

Solution

  • A day has 86400000 milliseconds. One hour has 3600000 milliseconds.

    Find the modulo and subtract it, so you'll obtain the start of the day, or hour. You are essentially removing the remainder of milliseconds in the integer division, rounding down.

    input_epoch = 1647548963623
    
    truncate_day_epoch = input_epoch - (input_epoch % 86400000)
    
    truncate_hour_epoch = input_epoch - (input_epoch % 3600000)