app.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
from urllib.parse import urlparse, parse_qs, urlencode, urlunparse def generate_youtube_timestamp_url(video_url, timestamp): # Convert hh:mm:ss to seconds if needed if isinstance(timestamp, str): parts = list(map(int, timestamp.split(":"))) if len(parts) == 3: timestamp = parts[0]*3600 + parts[1]*60 + parts[2] elif len(parts) == 2: timestamp = parts[0]*60 + parts[1] elif len(parts) == 1: timestamp = parts[0] else: raise ValueError("Invalid time format") # Parse URL parsed = urlparse(video_url) query = parse_qs(parsed.query) query['t'] = str(timestamp) # Reconstruct URL new_query = urlencode(query, doseq=True) new_url = urlunparse((parsed.scheme, parsed.netloc, parsed.path, parsed.params, new_query, parsed.fragment)) return new_url # Example usage: video_url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ" time_input = "1:23" # or just 83 timestamped_url = generate_youtube_timestamp_url(video_url, time_input) print("Timestamped URL:", timestamped_url) |