Home > OS >  How do I convert an API UTC time to local time ( 13:00)
How do I convert an API UTC time to local time ( 13:00)

Time:09-27

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

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

CodePudding user response:

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

CodePudding user response:

I solved the problem using the dateutil and pytz library

import requests
import pytz
from dateutil import parser

api_url = 'https://api.sunrise-sunset.org/json?lat=-43.525650&lng=172.639847&formatted=0'
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
  • Related