Search code examples
python-3.xpython-datetimepython-dateutil

convert string having timezone into to utc datetime object python


I have a timezone aware string like this and would like to convert it to utc timezone. I am using python 3.4 version

My string is like -

2018-05-04T05:22:52.3272611-04:00

I am not able to get much info on converting the given datetime to utc.


Solution

  • That looks like an ISO 8601 string (though with anomalously high precision on the sub-second component); if the fact that you have 7 digits instead of 6 after the decimal point is a typo, you can use dateutil.parser.isoparse on it:

    from dateutil.parser import isoparse
    from dateutil.tz import UTC
    
    dt = isoparse('2018-05-04T05:22:52.327261-04:00')
    dt.astimezone(UTC)
    

    Otherwise you can use dateutil.parser.parse, which is slower but allows for more unusual formats:

    from dateutil.parser import parse
    from dateutil.tz import UTC
    
    dt = parse('2018-05-04T05:22:52.3272611-04:00')
    dt.astimezone(UTC)
    

    You should also use parse if you are not certain what the format will be.