Answers for "get timezone of a timestamp python"

2

get local timezone python

import datetime

now = datetime.datetime.now()
local_now = now.astimezone()
local_tz = local_now.tzinfo
local_tzname = local_tz.tzname(local_now)
print(local_tzname)
Posted by: Guest on January-26-2021
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 "get timezone of a timestamp python"

Python Answers by Framework

Browse Popular Code Answers by Language