I am trying to convert a datetime from an API that stores datetime values as UTC. I need to convert the datetime to my local time ‘Pacific/Auckland’
The API I am using is Sunrise-Sunset https://sunrise-sunset.org/api
The specific location I am requesting is Christchurch, New Zealand https://sunrise-sunset.org/search?location=christchurch
import requests api_url = 'https://api.sunrise-sunset.org/json?lat=-43.525650&lng=172.639847&formatted=0' response = requests.get(api_url) if response.status_code == 200: sunset_today = response.json()['results']['sunset'] print(sunset_today) # outputs '2021-09-26T06:31:41+00:00'
I have searched StackOverflow and Google extensively, but cannot seem to find a solution that fits my needs.
The question I am asking is
- How can I convert the UTC value to my local datetime (‘Pacific/Auckland’)?
FYI, I don’t want to add bloat to the application, but from previous (unsuccessful) attempts at solving this problem I have already installed the
I am writing my application in Django 3.2.7 and have adjusted my settings.py
TIME_ZONE = 'Pacific/Auckland'
When trying to convert the string to a
datetime I get the following error.
time data ‘2021-09-26T06:31:41+00:00’ does not match format ‘%Y-%m-%dT%H:%M:%S %Z’
sunset_today = response.json()['results']['sunset'] format = '%Y-%m-%dT%H:%M:%S %Z' parsed_date = datetime.strptime(sunset_today, format) print(parsed_date) # ERROR: time data '2021-09-26T06:31:41+00:00' does not match format '%Y-%m-%dT%H:%M:%S %Z'*
To convert timezone aware string to python datetime easier to use
fromisoformat, since you are getting ISO formatted string from API anyway:
import datetime sunset_today = response.json()['results']['sunset'] parsed_date = datetime.datetime.fromisoformat(sunset_today) # 2021-09-26 06:31:41+00:00
Answered By – Gasanov
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0