1

I have a date with GMT with different timezones +6 & +5

gmt_time6= "2022-05-06T15:11:29.695GMT+06:00"
gmt_time5 = "2022-05-06T14:11:29.785GMT+05:00"

How to parse it, that final format will be

gmt_time_final6 = "2022-05-06 15:11:29.695000"
gmt_time_final5 = "2022-05-06 15:11:29.695000"
LOTR
  • 113
  • 1
  • 1
  • 10
  • "GMT+-" notation is… rare at best. There may be confusion as to how to interpret it. Either the timestamp is parsed as being in GMT, and then 6 hours are added/subtracted from it, *or* "GMT+-" notation triggers a different standard which defines "+-" offset notation exactly the other way around than the ISO standard does. Yes, that exists, I just can't find the reference for it at the moment. The best solution would be to switch to standard ISO notation `...13:56:57.940+06:00`. If that's not possible, some more manual parsing may be necessary. – deceze May 06 '22 at 09:12
  • @deceze I'm not sure regarding the reversed standard, but he has an example output showing +06:00 unaware is what he wants. No need for manual parsing besides removing the `GMT`. – Bharel May 06 '22 at 10:37

2 Answers2

2

First, remove the GMT designation:

date = "2022-05-06T15:11:29.695GMT+06:00".replace("GMT", "")

Then, parse it like any other ISO format:

from datetime import datetime, timezone, timedelta
dt = datetime.fromisoformat(date)

In your case, you want it as an ISO format unaware timezone +6 (meaning GMT+6 without showing the timezone):

result = dt.astimezone(timezone(timedelta(hours=6))).replace(tzinfo=None).isoformat(sep=" ")
print(result)

One line:

from datetime import datetime, timezone, timedelta
gmt_time5 = "2022-05-06T14:11:29.785GMT+05:00"
datetime.fromisoformat(gmt_time5.replace("GMT", "")).astimezone(timezone(timedelta(hours=6))).replace(tzinfo=None).isoformat(sep=" ")

Result: '2022-05-06 15:11:29.785000'

Bharel
  • 23,672
  • 5
  • 40
  • 80
1

I'm not sure according to what logic the explicit "GMT" in the string triggers weird behaviour in the dateutil parser*, but with a bit more explicit manual parsing it works just fine:

* In reference to an earlier version of the question.

>>> from datetime import datetime
>>> ts = '2022-05-06T15:11:29.695GMT+06:00'
>>> datetime.strptime(ts, '%Y-%m-%dT%H:%M:%S.%fGMT%z')
datetime.datetime(2022, 5, 6, 15, 11, 29, 695000, tzinfo=datetime.timezone(datetime.timedelta(seconds=21600)))
>>> datetime.strptime(ts, '%Y-%m-%dT%H:%M:%S.%fGMT%z').astimezone()
datetime.datetime(2022, 5, 6, 11, 11, 29, 695000, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), 'CEST'))
>>> datetime.strptime(ts, '%Y-%m-%dT%H:%M:%S.%fGMT%z').replace(tzinfo=None)
datetime.datetime(2022, 5, 6, 15, 11, 29, 695000)
deceze
  • 510,633
  • 85
  • 743
  • 889