0

For instance this:

my_timestamp = '2022-01-02T02:00:02-08:00'

We know that +00:00 is considered UTC, this timestamp -08:00 indicates America/Los_Angeles.

Is there any way to explicitly get that information using any date function in python?

For instance:

my_timestamp = '2022-01-02T02:00:02-08:00' # iso string
implicit_tz = someFunction(my_timestamp) # return the string "America/Los_Angeles"

Is this possible? Thanks!

Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44
amggg013
  • 91
  • 1
  • 7
  • Have you looked at the methods in the `datetime` module? – Barmar Feb 07 '22 at 19:06
  • Are you asking how to split the `-08:00` part from the string or how to look up the location "Los Angeles" given `-08:00`? – mkrieger1 Feb 07 '22 at 19:10
  • @Barmar yes I did, I couldnt find a method that gives the name of the timezone in a string. Please correct me I am wrong – amggg013 Feb 07 '22 at 19:10
  • @mkrieger1 how to get the "America/Los_Angeles"` – amggg013 Feb 07 '22 at 19:10
  • 1
    Does this answer your question? [How can I get a human-readable timezone name in Python?](https://stackoverflow.com/questions/3489183/how-can-i-get-a-human-readable-timezone-name-in-python) – mkrieger1 Feb 07 '22 at 19:11
  • 1
    "this timestamp -08:00 indicates America/Los_Angeles." Or America/Tijuana. Or America/Vancouver. Or Pacific/Pitcairn. How do you want your function to choose? – Sören Feb 07 '22 at 19:18
  • @Sören `America/Los_Angeles.` preferably – amggg013 Feb 07 '22 at 19:18
  • But it shouldnt matter really – amggg013 Feb 07 '22 at 19:19
  • You can use `dateutil.parser.parse` to convert your timestamp string into a `datetime` object that has a `tzoffset`. Then look at this https://stackoverflow.com/questions/35085289/getting-timezone-name-from-utc-offset to get a name from the offset. There can be multiple names for the same offset which is why this is not as trivial as it seems. – Ankur Feb 07 '22 at 19:45

1 Answers1

0

As per the comments above, this code will output all the possible timezones for your ISO string. Is up to you which one to choose.

from dateutil.parser import isoparse
import dateutil.tz as dtz
import pytz
my_timestamp = '2022-01-02T02:00:02-08:00' # iso string
my_timestamp_parsed = isoparse(my_timestamp)
my_timezone = isoparse(my_timestamp).tzinfo
for name in pytz.common_timezones:
    timezone=dtz.gettz(name)
    try:
        if timezone.utcoffset(my_timestamp_parsed) == my_timezone.utcoffset(my_timestamp_parsed):
            print(name)
    except AttributeError:
        pass
TheConfax
  • 144
  • 10