CMHammond

Timestamp Offset

Jun 17th, 2021 (edited)
497
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.81 KB | None | 0 0
  1. """
  2. Need to offset some timestamps in a YouTube comment by a constant value? This program is for you.
  3. I made this to fix any comments with timestamps on YouTube livestreams that had been edited after the fact.
  4. """
  5.  
  6.  
  7. numbers = ["0","1","2","3","4","5","6","7","8","9"]
  8.  
  9. #__________________________________________________________________________________________________________
  10.  
  11.  
  12. def convert(time, mode):
  13.            
  14.     if mode == "to seconds":
  15.        
  16.         #print("debugme:",time)
  17.         if time[0] != '-': positive = True
  18.        
  19.         else:
  20.             positive = False
  21.             time = time[1:]
  22.            
  23.         time += ':' # Marks end of string
  24.        
  25.         hms = 0
  26.         number = ""
  27.         seconds = 0
  28.        
  29.         #print("debugpos:",positive)
  30.        
  31.         for char in time:
  32.            
  33.             if char in numbers: number += char
  34.            
  35.             elif char == ":":
  36.                 if hms == 0: seconds += int(number) * 3600 # Convert hours to seconds
  37.                 elif hms == 1: seconds += int(number) * 60 # Convert minutes to seconds
  38.                 else: seconds += int(number) # No need to convert seconds any further.
  39.                 hms += 1  # Increment to move onto h/m/s.
  40.                 number = "" # Reset
  41.        
  42.        
  43.         if positive: return seconds
  44.         return -seconds
  45.        
  46.        
  47.     elif mode == "to h:m:s":
  48.         hours = time // 3600
  49.         minutes = str( (time % 3600) // 60 ).rjust(2, '0')
  50.         seconds = str( (time % 3600) % 60  ).rjust(2, '0')
  51.        
  52.         return f"{hours}:{minutes}:{seconds}"
  53.        
  54.        
  55. #__________________________________________________________________________________________________________
  56.  
  57.                                
  58. def query():
  59.     filename = input("Enter file name: ")
  60.     #filename = filename + ".txt"
  61.    
  62.    
  63.     while True:
  64.         offset = input("\nEnter offset: ") # Example input: "0:29:44"
  65.        
  66.         if offset[0] == "+":
  67.             sign = "+"
  68.             offset = offset[1:]
  69.         elif offset[0] == "-":
  70.             sign = "-"
  71.             offset = offset[1:]
  72.         else:
  73.             print("INFO: ± ommitted, defaulting to negative.")
  74.             sign = "-"
  75.            
  76.  
  77.         # Error handling
  78.         invalid = False
  79.    
  80.         if len(offset) != 7:
  81.             print("Invalid! Timestamp must be in this form ±h:mm:ss\n")
  82.             continue
  83.         for char in offset:
  84.             if (char not in numbers) and (char != ':'):
  85.                 print("Invalid! Timestamp must only contain numbers and colons (:) to seperate h/m/s.")
  86.                 invalid = True
  87.                 break
  88.                
  89.         if invalid: continue
  90.         elif (offset[2] in ["6","7","8","9"]) or (offset[5] in ["6","7","8","9"]):
  91.             print("\nInvalid! Minutes and seconds must not exceed 59.")
  92.             continue
  93.         else: break
  94.        
  95.     if sign == "+":
  96.         return filename, convert(offset, 'to seconds')
  97.     return filename, convert("-"+offset, 'to seconds')
  98.    
  99. #__________________________________________________________________________________________________________            
  100.                            
  101. def fix(line, offset):
  102.        
  103.     if not line:
  104.         print()
  105.         return line # Dealing with an empty line.
  106.        
  107.     line += ' ' # Marks end of line.
  108.    
  109.     index = 0
  110.     next = 0
  111.     text = ""
  112.     flag = False
  113.     to_fix = {}
  114.    
  115.     count = 1
  116.     # Checking each character in the line.
  117.     for i in range(len(line)-1): # Using range, so I can also index the end of the timestamp.
  118.  
  119.         if i < next: continue # Skips to end of timestamp, if previously found.
  120.         elif i == next and text != "":
  121.             text += line[i]
  122.            
  123.         next = i
  124.        
  125.    
  126.         try:
  127.            
  128.             # DETECTING A NUMBER, INDICATIVE OF A TIMESTAMP
  129.             if line[i] in numbers and line[i+7] not in numbers:
  130.                
  131.             # Testing for false positives ___________________________
  132.                 if line[i+1] != ':' or line [i+4] != ':':
  133.                     text += line[i]
  134.                     continue
  135.             #________________________________________________________
  136.                
  137.                 if text != "": # Avoids adding it at the beginning of the line.
  138.                     to_fix[str(count)] = text # Example: {"2", " - Game name (Trailer:"}
  139.                     text = "" # Reset
  140.                     count += 1
  141.                        
  142.                 to_fix[str(count)] = line[i:i+7] # Example: "1":"1:45:02"}
  143.                 count += 1
  144.                 next = i+7
  145.                
  146.             else: text += line[i] # Storing the text parts character by character.
  147.                
  148.         except IndexError: text += line[i]
  149.            
  150.         to_fix[str(count)] = text
  151.        
  152.     #print(to_fix)
  153.    
  154.     line = ""
  155.     for key in to_fix:
  156.         try:
  157.             if to_fix[key][0] in numbers:
  158.                 ts_inSeconds = convert(to_fix[key],"to seconds")
  159.                 to_fix[key] = convert(ts_inSeconds + offset, "to h:m:s")
  160.         except: pass   
  161.         line += to_fix[key]
  162.            
  163.     print(line) # Output to console.
  164.     return line
  165.    
  166.  
  167. #__________________________________________________________________________________________________________
  168.  
  169.  
  170. def start():
  171.    
  172.     filename, offset = query()
  173.     print(f"\nOffsetting by {offset}s...\n\n")
  174.    
  175.     with open((filename + ".txt"), 'r', encoding="utf-8") as f:
  176.         lines = f.readlines()
  177.    
  178.     #print(lines)
  179.     newlines = []
  180.    
  181.     count = 0
  182.     for line in lines:
  183.       count += 1
  184.       with open((filename + "_new.txt"), 'a', encoding="utf-8") as new:
  185.         new.write(fix( line.strip(), offset) +'\n')
  186. #__________________________________________________________________________________________________________
  187.  
  188. if __name__ == "__main__":
  189.     start()
Add Comment
Please, Sign In to add comment