dateutil can be installed using pip or easy_install, i.e. sudo pip install dateutil == 2.0 or sudo easy_install dateutil = = 2.0 . Version 2.0 for Python 3 compatibility is not required. Full documentation can be found at http://labix.org/python-dateutil .
Code: parsing examples
| tr> |
datetime.datetime (2010, 9, 25 , 10, 36, 28) datetime.datetime (2010, 9, 25, 10, 36) datetime.datetime (2010, 9, 25, 10, 36, 28) datetime.datetime (2010, 9, 25, 0, 0 ) datetime.datetime (2010, 9, 25, 10, 36, 28, tzinfo = tzutc ())
All you need for this — import the parser module and call the parse () function with the datetime string. The parser can return a reasonable datetime object, but it cannot parse the string, it will raise a ValueError.
How it works:
- Analyzer instead of looking for recognizable tokens, guess what these tokens refer to. It does not use regular expressions.
- The order of these tokens matters as it uses a date format that looks like month / day / year (default order), while others use day / month format / year.
- The parse () function accepts an optional key argument dayfirst, which is False by default to solve this problem.
- It can parse dates correctly in the latter format if it has set to True.
datetime.datetime (2016, 6, 16, 0, 0)
Another ordering problem can occur with two over the years. but & # 39; 11 -6-19 ′ — it is an ambiguous date format. Since by default dateutil is in month-day-year format, & # 39; 11 -6-19 ′ is parsed to 2019. But if yearfirst = True is passed to parse (), it can be parsed for 2011.
datetime.datetime (2019, 11, 6, 0, 0) datetime.datetime (2011, 6, 19, 0, 0)
The dateutil parser can also do fuzzy parsing and allows you to ignore extraneous characters in datetime string. parse () will raise a ValueError with a default value of False when it encounters unknown tokens. A datetime object can usually be returned if fuzzy = True.