Answers for "how to convert datetime object to different timezone python"

0

how to convert time from one timezone to another in python

from datetime import datetime
from pytz import timezone
format = "%Y-%m-%d %H:%M:%S %Z%z"
# Current time in UTC
now_utc = datetime.now(timezone('UTC'))
print(now_utc.strftime(format))
# Convert to Asia/Kolkata time zone
now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
print(now_asia.strftime(format))
Posted by: Guest on August-31-2020
0

convert timezone python

import pytz
from dateutil import tz
from datetime import datetime, timedelta
# must read source link else Bug:

NYC_p = pytz.timezone('America/New_York')   # 1.53 µs
NYC_d = tz.gettz('America/New_York')        # 863 ns
# tz Awareness
dt_p = NYC_p.localize(datetime(2018, 11, 1))    # 35.4 µs
dt_d = datetime(2018, 11, 1, tzinfo=NYC_d)      # 1.38 µs

dt_p.utcoffset()        # 655 ns
dt_d.utcoffset()        # 13.9 µs

LA_p = pytz.timezone('America/Los_Angeles')
LA_d = tz.gettz('America/Los_Angeles')
# tz Conversion
NYC_p.localize(datetime(2018, 11, 1)).astimezone(LA_p)  # 44.8 µs
datetime(2018, 11, 1, tzinfo=NYC_d).astimzone(LA_d)     # 32.8 µs

# ~~~~~ Date Arithmetic
dt_winter = datetime(2018, 2, 14, 12, tzinfo=NYC_d)
dt_spring = dt_winter + timedelta(days=60)
print(dt_spring)
# 2018-04-15 12:00:00-04:00 # correct

dt_winter = NYC_p.localize(datetime(2018, 2, 14, 12)) # potential Bug vector1
dt_spring = dt_winter + timedelta(days=60)
print(dt_spring)
# 2018-04-15 12:00:00-05:00 # incorrect. subtle gotcha!
print(NYC_p.normalize(dt_spring)) # potential Bug vector2
# 2018-04-15 13:00:00-04:00 # correct
Posted by: Guest on June-21-2021

Code answers related to "how to convert datetime object to different timezone python"

Python Answers by Framework

Browse Popular Code Answers by Language