How do I convert an API UTC time to local time (+13:00)


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

The specific location I am requesting is Christchurch, New Zealand

import requests

api_url = ''
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

  1. 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 tzlocal and pytz packages.

I am writing my application in Django 3.2.7 and have adjusted my 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)

# 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

Leave a Reply

(*) Required, Your email will not be published