Convert Date to Python Date

I'm trying to check if dates match dates. I use the dateutil library, but I get strange results. For example, when I try to do the following:

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

I get a result 1984-10-12T00:00:00that is incorrect. Does anyone know why this one 12is being added to a date?

+4
source share
2 answers

12- The current date. dateutilaccepts components from the current date / time to account for the missing date or year in the date (this is not done for the month, only the date or year). As in another example, it will be a date - Janauary 20- it will be analyzed as 2015/01/12taking 2015 from the current time and time.

, - , .

, datetime, , datetime.datetime.strptime , ValueError. -

def isdate(dt, fmt):
    try:
        datetime.datetime.strptime(dt, fmt)
        return True
    except ValueError:
        return False

validformats = [...]
dates =[...]

for x in dates:
    if any(isdate(x,fmt) for fmt in validformats):
        print(x, 'is valid date')
+1

parse() datetime, . default , today.

, 12 , ( ), .

, , , try ... except .

import dateutil.parser as parser
x = '10/84'
try:
    date = (parser.parse(x))
    print(date.isoformat())
except ValueError as err:
    pass # handle the error
+5

Source: https://habr.com/ru/post/1611357/


All Articles