Last active
April 20, 2021 09:13
-
-
Save cupracer/d109c0fbf55929626426dba0dc23ca7a to your computer and use it in GitHub Desktop.
Calculate timestamps by adding or subtracting 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/python3 | |
import sys | |
import re | |
from datetime import datetime, timedelta | |
if not len(sys.argv) == 4: | |
print('\n * usage: ' + sys.argv[0] + ' %Y-%m-%d-%H:%M[:%S] add|sub #seconds\n') | |
exit(1) | |
start_date = sys.argv[1] | |
action = sys.argv[2] | |
seconds = int(sys.argv[3]) | |
difference = timedelta(seconds=seconds) | |
pattern_with_seconds = re.compile("^[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2}:[0-9]{2}:[0-9]{2}$") | |
pattern_without_seconds = re.compile("^[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2}:[0-9]{2}$") | |
if re.match(pattern_with_seconds, start_date): | |
source_date = datetime.strptime(start_date, '%Y-%m-%d-%H:%M:%S') | |
elif re.match(pattern_without_seconds, start_date): | |
source_date = datetime.strptime(start_date, '%Y-%m-%d-%H:%M') | |
else: | |
print('wrong timestamp format') | |
exit(1) | |
print('\nGiven timestamp: ' + start_date, end =" ") | |
if action == 'add': | |
result_date = source_date + timedelta(seconds = seconds) | |
print('+', end =" ") | |
elif action == 'sub': | |
result_date = source_date - timedelta(seconds = seconds) | |
print('-', end =" ") | |
print(str(seconds) + ' = ' + str(result_date) + ' (Difference ' + str(difference) + ')' + '\n') | |
# | |
# EXAMPLES: | |
# | |
# $ ./timestamp.py | |
# | |
# * usage: ./test.py %Y-%m-%d-%H:%M[:%S] add|sub #seconds | |
# | |
# | |
# $ ./timestamp.py 2021-04-17-12:17:20 add 4700 | |
# | |
# Given timestamp: 2021-04-17-12:17:20 + 4700 = 2021-04-17 13:35:40 (Difference 1:18:20) | |
# | |
# | |
# $ ./timestamp.py 2021-04-17-12:17:20 sub 65400 | |
# | |
# Given timestamp: 2021-04-17-12:17:20 - 65400 = 2021-04-16 18:07:20 (Difference 18:10:00) | |
# | |
# | |
# $ ./timestamp.py 2021-04-17-12:17 add 88423 | |
# | |
# Given timestamp: 2021-04-17-12:17 + 88423 = 2021-04-18 12:50:43 (Difference 1 day, 0:33:43) | |
# | |
# | |
# $ ./timestamp.py 2021-04-17-12:17 sub 18402739 | |
# | |
# Given timestamp: 2021-04-17-12:17 - 18402739 = 2020-09-16 12:24:41 (Difference 212 days, 23:52:19) | |
# |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment