0

My datetime looks like this:

date_time =  "2022-02-17 08:29:36.345374"

I want to convert this to another timezone, the API which I am using have a info of for example userTimeZone = -300. I tried to search but can't locate that from this userTimeZone I can get my timezone time.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
voicenob
  • 31
  • 7
  • Does [Python: How do you convert a datetime/timestamp from one timezone to another timezone?](https://stackoverflow.com/questions/31977563/python-how-do-you-convert-a-datetime-timestamp-from-one-timezone-to-another-tim) answer your question? – wwii Apr 04 '22 at 22:15
  • What does -300 even mean? Is that in minutes, i.e. `-0500`? – jonrsharpe Apr 04 '22 at 22:17
  • @wwii no sir , I just have info like -330 , 300 etc , – voicenob Apr 04 '22 at 22:17

1 Answers1

1

You can create a timezone given an offset via timedelta (I'm assuming -300 is in minutes, equivalent to -5 hours):

>>> from datetime import datetime, timedelta, timezone
>>> tz = timezone(timedelta(minutes=-300))
>>> tz
datetime.timezone(datetime.timedelta(days=-1, seconds=68400))
>>> tz.tzname(None)
'UTC-05:00'

Once you've parsed the date_time string (which I'm assuming is in UTC) to an actual datetime:

>>> dt = datetime.strptime(date_time, "%Y-%m-%d %H:%M:%S.%f")
>>> dt
datetime.datetime(2022, 2, 17, 8, 29, 36, 345374)

you can apply the offset to see what the local time would be:

>>> local = dt.astimezone(tz)
>>> local
datetime.datetime(2022, 2, 17, 3, 29, 36, 345374, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=68400)))
>>> local.isoformat()
'2022-02-17T03:29:36.345374-05:00'
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437