Untitled
from datetime import datetime import pytz def convert_to_utc(timestamp_str, timezone_str): # Parse the timestamp string into a datetime object local_dt = datetime.strptime(timestamp_str, '%Y-%m-%d %I:%M:%S %p') # Assign the timezone to the datetime object local_tz = pytz.timezone(timezone_str) local_dt = local_tz.localize(local_dt) # Convert to UTC utc_dt = local_dt.astimezone(pytz.utc) return utc_dt.strftime('%Y-%m-%d %H:%M:%S UTC') # Adjusted to use 24-hour format and explicitly label as UTC # Example usage: timestamp = '2025-01-20 08:34:54 PM' timezone = 'America/New_York' utc_timestamp = convert_to_utc(timestamp, timezone) print(utc_timestamp)
Leave a Comment