Ryan Thomas
Ryan Thomas

Reputation: 536

Display datetime local timezones

I am pretty new to this so not sure how it works, I have tried reading up but think I just need a straightforward explanation to what is probably a basic question.

From an API I am getting a baseball schedule and the dates comes through as a datetime object like this '2021-04-15T02:10:00.000Z'.

I know the Z means UTC time, but will it display in local time where ever the user is?

If I save it as a DateTimeField in my model, how can I pass it through to my template as the users local time?

Thanks in advance for your help!

Upvotes: 0

Views: 116

Answers (1)

FObersteiner
FObersteiner

Reputation: 25564

Parse to datetime - Your input is nicely formatted according to ISO 8601, you can parse to datetime object like I've shown here.

from datetime import datetime

s = "2021-04-15T02:10:00.000Z"
dtobj = datetime.fromisoformat(s.replace('Z', '+00:00'))

print(repr(dtobj))
# datetime.datetime(2021, 4, 15, 2, 10, tzinfo=datetime.timezone.utc)

Convert to local time - Now you can convert with the astimezone method to the time zone your machine is configured to use like (see also this):

dt_local = dtobj.astimezone(None) # None here means 'use local time from OS setting'

print(repr(dt_local))
# datetime.datetime(2021, 4, 15, 4, 10, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), 'Mitteleuropäische Sommerzeit'))

# Note: my machine is on Europe/Berlin, UTC+2 on the date from the example

Convert to another time zone - If you want to convert to another time zone, grab a time zone object e.g. from the zoneinfo lib (Python 3.9+) and do the conversion like:

from zoneinfo import ZoneInfo

time_zone = ZoneInfo('America/Denver')
dt_denver= dtobj.astimezone(time_zone)

print(repr(dt_denver))
# datetime.datetime(2021, 4, 14, 20, 10, tzinfo=zoneinfo.ZoneInfo(key='America/Denver'))

See here how to get a list of available time zones.

Upvotes: 1

Related Questions