Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

datetime - How to convert UTC time pulled from an API into local time using Python?

I currently have a field I'm pulling from an API called "categorized-at" that has this format:

"23/7/2020"

However, this API uses UTC+0000 time, but we need this to be in -0600 time. We submitted a ticket to the place that hosts the API asking for help and they were unable to assist us. However, I've made good process and have this chunk of code:

from datetime import datetime, timezone, timedelta
import time
from dateutil import tz

from_zone = tz.tzutc()
to_zone = tz.tzlocal()
utc = datetime.strptime('23/7/2020', '%d/%m/%Y')
utc = utc.replace(tzinfo=from_zone)
central = utc.astimezone(to_zone)

This works perfectly, but only if I include a specific date in the parameter of datetime.strptime - however, this needs to be applied to the "categorized_at" field for a report with thousands of values that needs to be automated. I tried to just include "categorized_at" in there like this:

utc = datetime.strptime('categorized_at', '%d/%m/%Y')

but no matter how I try and adjust the date formatting, I get the error

'time data "categorized at' does not match '%d/%m/%Y'

I feel like the solution here is something simple I'm overlooking, and any help would be appreciated.

question from:https://stackoverflow.com/questions/65832961/how-to-convert-utc-time-pulled-from-an-api-into-local-time-using-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...