To use time in ISO 8601 format in Python?

Asked 2 years ago, Updated 2 years ago, 160 views

"2008-09-03T20:56:35.450686Z" Same RFC 3339 string I'd like to turn it over to Python datetime.datetime type. I looked it up and it only came out in a Unix time stamp format What about RFC 3339?

python parsing datetime iso8601 rfc3339

2022-09-22 22:27

1 Answers

Starting with Python 2.6, the ability to support microseconds has been added to convert strings of type RFC 3339 to datetime.datetime.

datetime.datetime.strptime(date_string, format) receives date_string Returns the datetime.datetime object that matches the format.

datetime.datetime.strptime("2008-09-03T20:56:35.450686Z", "%Y-%m-%dT%H:%M:%S.%fZ")

In short, dateutil.parse.parse(timestr, parserinfo=None, **kwargs) takes the date/time stamp in string format as a factor and returns the datetime.datetime object.

dateutil is an RFC 3339 type string It also supports IOS 8601 date/time strings that are not compiled into RFC 3339, so it is recommended if you need to write a lot of time-related code.

Usage:

import dateutil.parser
print "RFC 3339\t\t\t, 2008-09-03T20:56:35.450686Z:", dateutil.parser.parse('2008-09-03T20:56:35.450686Z') # RFC 3339 format
print "ISO 8601 extended\t, 2008-09-03T20:56:35.450686", dateutil.parser.parse('2008-09-03T20:56:35.450686') # ISO 8601 extended format
print "IOS 8601 basic\t\t, 0080903T205635.450686", dateutil.parser.parse('20080903T205635.450686') # ISO 8601 basic format
print "IOS 8601 basic(date), 20080903", dateutil.parser.parse('20080903') # ISO 8601 basic format, date only

Result:

RFC 3339            , 2008-09-03T20:56:35.450686Z: 2008-09-03 20:56:35.450686+00:00
ISO 8601 extended   , 2008-09-03T20:56:35.450686 2008-09-03 20:56:35.450686
IOS 8601 basic      , 0080903T205635.450686 2008-09-03 20:56:35.450686
IOS 8601 basic(date), 20080903 2008-09-03 00:00:00


2022-09-22 22:27

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.