Convert Time Zones using Python

The following are two Python scripts to convert time zones. The second Python script I will share with you will allow the end user to enter the time zones.

Convert Time Zones using Python
Photo by Vince Veras / Unsplash

The following are two Python scripts to convert time zones.

import pytz
from datetime import datetime

# Set up the timezone information
source_timezone = pytz.timezone('America/Los_Angeles')
destination_timezone = pytz.timezone('Asia/Tokyo')

# Get the current time in the source timezone
source_time = datetime.now(source_timezone)

# Convert the time to the destination timezone
destination_time = source_time.astimezone(destination_timezone)

# Print the converted time
print(f'The current time in {destination_timezone.zone} is {destination_time.strftime("%Y-%m-%d %H:%M:%S")}')

The second Python script I will share with you will allow the end user to enter the time zones.

import pytz
from datetime import datetime

# Get the source timezone from user input
source_tz_str = input('Enter the source timezone: ')
source_timezone = pytz.timezone(source_tz_str)

# Get the destination timezone from user input
destination_tz_str = input('Enter the destination timezone: ')
destination_timezone = pytz.timezone(destination_tz_str)

# Get the current time in the source timezone
source_time = datetime.now(source_timezone)

# Convert the time to the destination timezone
destination_time = source_time.astimezone(destination_timezone)

# Print the converted time
print(f'The current time in {destination_timezone.zone} is {destination_time.strftime("%Y-%m-%d %H:%M:%S")}')