Python - Convert string representation of date to ISO 8601

后端 未结 2 509
南笙
南笙 2020-12-01 09:59

In Python, how can I convert a string like this:

Thu, 16 Dec 2010 12:14:05 +0000

to ISO 8601 format, while keeping the timezone?

2条回答
  •  情书的邮戳
    2020-12-01 10:38

    Python inbuilt datetime package has build in method to convert a datetime object to isoformat. Here is a example:

    >>>from datetime import datetime
    >>>date = datetime.strptime('Thu, 16 Dec 2010 12:14:05', '%a, %d %b %Y %H:%M:%S')
    >>>date.isoformat()
    

    output is

    '2010-12-16T12:14:05'
    

    I wrote this answer primarily for people, who work in UTC and doesn't need to worry about time-zones. You can strip off last 6 characters to get that string.

    Python 2 doesn't have very good internal library support for timezones, for more details and solution you can refer to this answer on stackoverflow, which mentions usage of 3rd party libraries similar to accepted answer.

提交回复
热议问题