Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dateutil date conversion

I'm trying to see if a list of dates are valid dates. I'm using the dateutil library, but I'm getting weird results. For example, when I try the following:

import dateutil.parser as parser
x = '10/84'
date = (parser.parse(x))
print(date.isoformat())

I get the result 1984-10-12T00:00:00 which is wrong. Does anyone know why this 12 gets added to the date?

like image 500
ray smith Avatar asked Oct 13 '15 02:10

ray smith


People also ask

Is dateutil built into Python?

dateutil is a third party module. It has recently been ported to Python 3 with dateutil 2.0, and the parser functions was ported as well. So the replacement is dateutil.

How do you parse a date in Python?

Python has a built-in method to parse dates, strptime . This example takes the string “2020–01–01 14:00” and parses it to a datetime object. The documentation for strptime provides a great overview of all format-string options.


1 Answers

The parse() method parses the string and updates a default datetime object, using the parsed information. If the default is not passed into this function, it uses first second of today.

This means that the 12 in your result, is today (when you're running the code), only the year and the month are updated from parsing the string.

If you need to parse the date string but you're not sure if it's a valid date value, then you may use a try ... except block to catch parse errors.

import dateutil.parser as parser
x = '10/84'
try:
    date = (parser.parse(x))
    print(date.isoformat())
except ValueError as err:
    pass # handle the error
like image 55
farzad Avatar answered Sep 20 '22 17:09

farzad