How do I parse an ISO 8601-formatted date?

后端 未结 27 2373
小鲜肉
小鲜肉 2020-11-21 06:08

I need to parse RFC 3339 strings like \"2008-09-03T20:56:35.450686Z\" into Python\'s datetime type.

I have found strptime in the Python sta

27条回答
  •  醉酒成梦
    2020-11-21 06:31

    One straightforward way to convert an ISO 8601-like date string to a UNIX timestamp or datetime.datetime object in all supported Python versions without installing third-party modules is to use the date parser of SQLite.

    #!/usr/bin/env python
    from __future__ import with_statement, division, print_function
    import sqlite3
    import datetime
    
    testtimes = [
        "2016-08-25T16:01:26.123456Z",
        "2016-08-25T16:01:29",
    ]
    db = sqlite3.connect(":memory:")
    c = db.cursor()
    for timestring in testtimes:
        c.execute("SELECT strftime('%s', ?)", (timestring,))
        converted = c.fetchone()[0]
        print("%s is %s after epoch" % (timestring, converted))
        dt = datetime.datetime.fromtimestamp(int(converted))
        print("datetime is %s" % dt)
    

    Output:

    2016-08-25T16:01:26.123456Z is 1472140886 after epoch
    datetime is 2016-08-25 12:01:26
    2016-08-25T16:01:29 is 1472140889 after epoch
    datetime is 2016-08-25 12:01:29
    

提交回复
热议问题