End of Day timestamp with Daylight Saving transitions

What is the best way to implement a function to produce the END OF DAY timestamp as “yyyy-MM-dd 23:59:59” for a timestamp that is safe for Daylight Savings transitions ?

I had been using a simple offset from midnight of +24hrs and -1 second as:

eod_ts = system.date.addSeconds(system.date.addHours(system.date.midnight(input_ts),24), -1)

But that breaks for a Date where Daylight savings commences or ends.
So I added more logic to adjust the hours offset as follows:

def get_endOfDay(input_ts):

    # check if Daylight Savings transition occurs on input date
    amInDls = system.date.isDaylightTime(system.date.midnight(input_ts))
    pmInDls = system.date.isDaylightTime(system.date.addSeconds(system.date.addHours(system.date.midnight(input_ts),12), -1))

    if not amInDls and pmInDls :
	# "Spring forward"
	offsetHours = 23
     elif amInDls and not pmInDls :
	# "Fall back"
	offsetHours = 25
	offsetHours = 24

     return system.date.addSeconds(system.date.addHours(system.date.midnight(input_ts),offsetHours), -1)

It works, but is there a better way to do this?

I would use something like this:

from java.util import Date
def getEndOfDay(input_ts):
	beginning = Date(input_ts.year, input_ts.month, input_ts.date, 0, 0, 0)
	return system.date.addDays(beginning, 1)

Note that using SQL comparisons of the form t_stamp <= ‘… 23:59:59’ is suboptimal. If your DB stores fractional seconds, you will omit records that occur in that last second. The function above returns the beginning of the next day as the end of the given day, as that is always safe to use with a pure ‘less-than’ comparison. No matter what resolution your DB uses for timestamps.

Thank you Phil, I really appreciate all your valued posts to the Forum

1 Like