Skip to content

Instantly share code, notes, and snippets.

@Rainyan
Last active March 25, 2023 03:27
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Rainyan/a24e36b2d626121ac57dc9bc75c1afc3 to your computer and use it in GitHub Desktop.
For "HOURS:MINUTES:SECONDS" start-end timestamp pair, return the difference in seconds.
#!/usr/bin/env python3
# License: MIT. https://github.com/Rainyan
from datetime import datetime
import sys
# Usage:
# $ python timestamp_delta.py 00:12:34 02:01:13
# $ 6519
def timestamp_delta(start: str, end: str) -> int:
"""For "HOURS:MINUTES:SECONDS" start-end timestamp pair,
return the difference in seconds.
If hours are omitted, assumes 0 hours.
If hours and minutes are omitted, assumes 0 hours and minutes.
If end time is earlier than start time, returns a negative difference.
Max supported timestamp value is 23:59:59.
TODO: support >23:59:59 times
"""
start_parts = start.split(":")
assert len(start_parts) > 0
assert len(start_parts) <= 4
start_parts = ["0"] * (abs(len(start_parts) - 3)) + start_parts
assert int(start_parts[0]) < 24, "Max supported timestamp value is 23:59:59."
start = ":".join(start_parts)
end_parts = end.split(":")
assert len(end_parts) > 0
assert len(end_parts) <= 4
end_parts = ["0"] * (abs(len(end_parts) - 3)) + end_parts
assert int(end_parts[0]) < 24, "Max supported timestamp value is 23:59:59."
end = ":".join(end_parts)
format = "%H:%M:%S"
time_start = datetime.strptime(start, format)
time_end = datetime.strptime(end, format)
if time_end > time_start:
return (time_end - time_start).seconds
return -(time_start - time_end).seconds
if __name__ == "__main__":
print(timestamp_delta(sys.argv[1], sys.argv[2]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment