Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Timezone problem #16

Open
marcinpr opened this issue Sep 26, 2023 · 3 comments
Open

Timezone problem #16

marcinpr opened this issue Sep 26, 2023 · 3 comments

Comments

@marcinpr
Copy link

marcinpr commented Sep 26, 2023

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
Copy link
Author

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
Copy link
Owner

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

@Bliph
Copy link

Bliph commented Feb 18, 2024

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())

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants