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"
CodePudding user response:
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'
CodePudding user response:
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)