Home > Software engineering >  Date and time with time zone
Date and time with time zone

Time:04-05

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.

CodePudding user response:

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

>>> 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)))
>>> str(local)
'2022-02-17 03:29:36.345374-05:00'
  • Related