Python – Convert Timezone from EST to UTC

When looking at logs, they are usually UTC. This script helps convert the time zone from EST to UTC & UTC (Daylight Savings).

# Author: Kerry Cordero
# Version: 1.0.0
# Description: This script prompts for EST time with AM/PM, it outputs the UTC/UTCDL

from datetime import datetime, timedelta
from pytz import timezone

# Define the time zones
est = timezone('US/Eastern')
utc = timezone('UTC')

# Prompt the user for a time
time_str = input("Please enter a time in the format HH:MM AM/PM: ")

# Parse the time string
time_part, am_pm = time_str.split()
hour, minute = map(int, time_part.split(':'))

# Adjust hour for 12-hour format
if am_pm.upper() == 'PM' and hour != 12:
    hour += 12
elif am_pm.upper() == 'AM' and hour == 12:
    hour = 0

# Create a datetime object with the current date and the user-specified time
dt_est = datetime.now(est).replace(hour=hour, minute=minute)

# Convert the EST time to UTC
dt_utc = dt_est.astimezone(utc)

# Output the UTC time
print(f"The corresponding UTC time is {dt_utc.strftime('%H:%M')}")

# For daylight saving time in EST
if dt_est.dst() != timedelta(0):
    dt_edt = dt_est + dt_est.dst()
    dt_utc_dst = dt_edt.astimezone(utc)
    print(f"The corresponding UTC time during daylight saving (EDT) is {dt_utc_dst.strftime('%H:%M')}")