xxxxxxxxxx
import datetime
# Get the current UTC time
utc_now = datetime.datetime.utcnow()
# Convert UTC time to local time
local_now = utc_now + datetime.timedelta(hours=datetime.datetime.now().hour - utc_now.hour)
# Print the local time
print("Local time:", local_now)
xxxxxxxxxx
from datetime import datetime
from dateutil import tz
# METHOD 1: Hardcode zones:
from_zone = tz.gettz('UTC')
to_zone = tz.gettz('America/New_York')
# METHOD 2: Auto-detect zones:
from_zone = tz.tzutc()
to_zone = tz.tzlocal()
# utc = datetime.utcnow()
utc = datetime.strptime('2011-01-21 02:37:21', '%Y-%m-%d %H:%M:%S')
# Tell the datetime object that it's in UTC time zone since
# datetime objects are 'naive' by default
utc = utc.replace(tzinfo=from_zone)
# Convert time zone
central = utc.astimezone(to_zone)
xxxxxxxxxx
import datetime
import pytz
# Get the current local time
local_time = datetime.datetime.now()
# Get the local timezone
local_timezone = pytz.timezone('Your_Local_Time_Zone')
# Convert local time to UTC
utc_time = local_time.astimezone(pytz.UTC)
# Print the converted time
print("Local Time:", local_time)
print("UTC Time:", utc_time)
xxxxxxxxxx
from datetime import datetime, timezone
def utc_to_local(utc_dt):
return utc_dt.replace(tzinfo=timezone.utc).astimezone(tz=None)