kylebarron / suncalc-py

A Python port of suncalc.js for calculating sun position and sunlight phases
MIT License
60 stars 8 forks source link

Timezone problem #16

Open marcinpr opened 9 months ago

marcinpr commented 9 months ago

There is a problem to convert times received from get_times() to format "%H:%M:%S %Z" in other time zones than UTC. I assume that: sunrise = get_times(date, lat, lon)['sunrise'] saves the sunrise time with local zone instead of UTC. Maybe the objects returned by get_times should have timezone (UTC) specified? Please compare: print(get_times(date, lat, lon)['sunrise'].strftime('%H:%M:%S %Z')) print(datetime.now().strftime('%H:%M:%S %Z')) Both gives the answer without timezone info.

How to print the sunrise time, adding timezone info?

marcinpr commented 9 months ago

I have found a solution to my question from the last sentence:

sunrise_aware = pytz.timezone('UTC').localize(suncalc.get_times(date, lon, lat)['sunrise']) print(sunrise_aware.astimezone().strftime("%H:%M:%S %Z"))

Is there any simpler solution?

kylebarron commented 9 months ago

I don't know; timezones are hard! If you'd like to improve the docs, a PR is welcome

Bliph commented 4 months ago

I do not know if this is "simpler", but I always like to keep timestamps in epoch. After all, this is just a number.

from datetime import datetime, timezone
import time
from suncalc import get_position, get_times

lon = 7.0
lat = 58.0

# Get "today"
utc_now = datetime.fromtimestamp(time.time(), timezone.utc)

# Extract sunrise "today"
solar_times = get_times(date=utc_now, lng=lon, lat=lat)

# Extract sunrise epoch [s]
ts_sunrise_epoch = solar_times.get("sunrise").timestamp()

# Convert to local timezone
local_zone = datetime.now().astimezone().tzinfo
ts_sunrise_local = datetime.fromtimestamp(ts_sunrise_epoch, local_zone)

print(ts_sunrise_local.isoformat())