While reviewing my past answers, I noticed I'd proposed code such as this:
import time def dates_between(start, end): # muck around between the 9k+ time representation systems in Python # now start and end are seconds since epoch # return [start, start + 86400, start + 86400*2, ...] return range(start, end + 1, 86400)
When rereading this piece of code, I couldn't help but feel the ghastly touch of Tony the Pony on my spine, gently murmuring "leap seconds" to my ears and other such terrible, terrible things.
When does the "a day is 86,400 seconds long" assumption break, for epoch definitions of 'second', if ever? (I assume functions such as Python's time.mktime
already return DST-adjusted values, so the above snippet should also work on DST switching days... I hope?)
In prediction of tides, an epoch is a period of 19 years, representing one complete cycle of all possible alignments of the sun and the moon. In astronomy, an epoch is the point in time where a calendar, or a defined time frame within a calendar, is considered to begin.
Epoch Time Difference FormulaMultiply the two dates' absolute difference by 86400 to get the Epoch Time in seconds – using the example dates above, is 319080600.
Whenever doing calendrical calculations, it is almost always better to use whatever API the platform provides, such as Python's datetime and calendar modules, or a mature high-quality library, than it is to write "simpler" code yourself. Date and calendar APIs are ugly and complicated, but that's because real-world calendars have a lot of weird behavior.
For example, if it is "10:00:00 AM" right now, then the number of seconds to "10:00:00 AM tomorrow" could be a few different things, depending on what timezone(s) you are using, whether DST is starting or ending tonight, and so on.
Any time the constant 86400 appears in your code, there is a good chance you're doing something that's not quite right.
And things get even more complicated when you need to determine the number of seconds in a week, a month, a year, a quarter, and so on. Learn to use those calendar libraries.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With