Python UTC to Local DateTime
Example code to extract a serialized from JSON response with a property named period_end expressed as an ISO8601 timestamp string value to a localized python DateTime
JSON data response data is of this format
{
"forecasts": [
{
"pv_estimate": 0,
"period_end": "2018-12-26T16:25:00.0000000Z",
"period": "PT5M"
},
...
}
This code snippet will get the data and format it into a CSVish type output
from tzlocal import get_localzone
from isodate import parse_datetime, parse_duration
import requests
def main():
response = requests.get(
url='https://<api_url>',
params={
'format': 'json',
'hours': 48
},
)
for forecast_interval in response.json()['forecasts']:
period_end_utc = parse_datetime(forecast_interval['period_end'])
period_end_local = parse_datetime(forecast_interval['period_end']).astimezone(get_localzone())
period = parse_duration(forecast_interval['period'])
pv_estimate = forecast_interval['pv_estimate']
print(f'{period_end_utc},{period_end_local},{period},{pv_estimate}')
if __name__ == "__main__":
main()
The output of this should look like this now then
2018-12-26 04:00:00+00:00,2018-12-25 22:00:00-06:00,0:05:00,24.7
2018-12-26 04:05:00+00:00,2018-12-25 22:05:00-06:00,0:05:00,23.88