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 settings.py TIME_ZONE = 'Pacific/Auckland'

Edit 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'* 
8

2 Answers

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 
2

I solved the problem using the dateutil and pytz library

import requests import pytz from dateutil import parser api_url = ' response = requests.get(api_url) nz_zone = pytz.timezone('Pacific/Auckland') if response.status_code == 200: sunset_today = response.json()['results']['sunset'] converted_date = parser.parse(sunset_today).astimezone(nz_zone) print(converted_date) # outputs 2021-09-26 19:31:41+13:00 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like