I am getting 2 different strings
from 2 different sources and I would like to convert these strings to common date-time format
in UTC timezone
.
The 1st string value is like this : 2017-03-30T13:54:40+0300
and the 2nd string value is like this : Thu Jul 6 16:57:50 2017 +0530
.
I am new to Python and Python 3.6 and it will be great if someone can help me.

- 1,793
- 2
- 20
- 24

- 1
- 3
-
1Possible duplicate of [Converting string into datetime](https://stackoverflow.com/questions/466345/converting-string-into-datetime) – cosinepenguin Sep 06 '17 at 15:02
-
@cosinepenguin: I've scanned the question you mention, and the answers, and don't see how this is a duplicate. – Bill Bell Sep 08 '17 at 14:11
2 Answers
I could solve the problem using first by converting the strings to datetime format ( the formatting was tricky part here) and later by converting the these datetimes to local time zone using astimezone function in datetime module. Thanks everyone for the help. @Rohit Poudel, the link shared helped me understand date-times in python better.Can you please check if this is indeed duplicate of the mentioned link and if not , mark as non-duplicate as I am a newbie.

- 1
- 3
For the ISO8601 format string (your 1st string) do this:
Install these modules (Linux assumed, and assuming you have pip installed):
$ pip install iso8601 pytz
Then in your Python console:
>>> import datetime, iso8601, pytz
>>> s1 = '2017-03-30T13:54:40+03:00'
>>> s1a = '2017-03-30T13:54:40.123456+03:00' # with fraction of sec. added
>>> dt1 = iso8601.parse_date(s1)
>>> dt1
datetime.datetime(2017, 3, 30, 13, 54, 40, tzinfo=datetime.timezone(datetime.timedelta(seconds=10800), '+03:00'))
>>> dt1a = iso8601.parse_date(s1a)
>>> dt1a
datetime.datetime(2017, 3, 30, 13, 54, 40, 123456, tzinfo=datetime.timezone(datetime.timedelta(seconds=10800), '+03:00'))
dt1 and dt1a are instances of datetime.datetime. They are "aware" times bearing your +03:00 timezone offset.
Now convert that into UTC times:
>>> dt1a.astimezone(tz=pytz.utc)
datetime.datetime(2017, 3, 30, 10, 54, 40, 123456, tzinfo=<UTC>)
If you wanted the results in ISO8601 format, do this:
>>> dt1a.astimezone(tz=pytz.utc).isoformat()
'2017-03-30T10:54:40.123456+00:00'
You can see that in the last line, the time is 10:54.40.123456 UTC whereas the original was 13:54:40.123456+03:00.
For your second string, convert it to instances of datetime.datetime then proceed as above.

- 4,695
- 1
- 10
- 11
-
Alternatively, without needing pytz, do this: >>> dt1a.astimezone(tz=datetime.timezone.utc) – DeanM Dec 25 '18 at 17:05