0

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!

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
Ryan Thomas
  • 488
  • 4
  • 14
  • I've added an answer for the first part; the second part of your question reads as if it would be better to make it at least one separate, specific question (What do you mean by "DateTimeField", what is your "model", which "template", what "user", how do you obtain the user's time zone?). – FObersteiner Apr 15 '21 at 06:38

1 Answers1

1

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.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72