Answers for "date to timezone python"

1

python time now other timezone

#as an aware datetime
from datetime import datetime, timezone

utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time


#or from pytz database
import pytz

tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)
Posted by: Guest on December-16-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

Python Answers by Framework

Browse Popular Code Answers by Language