For "HOURS:MINUTES:SECONDS" start-end timestamp pair, return the difference in seconds.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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