简体   繁体   中英

Checking a date with three different date type libraries

I have a list of different dates. I want to test if the value in list is valid date or not. I have tried to do it but the statement which I gave isn't working well. How do I do it?

list1 = ['201222020','20-12-2020','12122020', '53122020']
valid=[]
invalid=[]
for l in list1:
    try:
        x = dateutil.parser.parse(str(l)) or dt.strptime(str(l),'%m%d%Y') or dt.strptime(str(l),'%d%m%Y')
        valid.append(x)
    
    except:
        invalid.append(l)
print(valid)
print(invalid)

Which gives:

valid = [datetime.datetime(2020, 12, 20, 0, 0)]
invalid = ['201222020', '12122020', '53122020']

But in real life dates like this '201222020','12122020' should also be accepted, which happens by using the other statement after or and this value '53122020' should be rejected.

In my scenario it's coming as above. Where am I going wrong? How to align the statements in correct way so that the list will be checked one after the other (first date until and then datetime('%m%d%Y') and then datetime('%d%m%Y') by all three?

Actual output:

 valid = [datetime.datetime(2020, 20, 2, 0, 0), datetime.datetime(2020, 12, 20, 0, 0), datetime.datetime(2020, 12, 12, 0, 0)]
invalid = ['53122020']

You could create a function that tries a set of other functions to parse the input. Those latter functions could be dateutil.parser.parse , datetime.strptime or whatever you choose. If all fail, the input is invalid.

Ex:

from datetime import datetime
import dateutil

def validate(datestring, vd_funcs, vd_args):
    """
    a function that tests if a datestring can be parsed by one of the functions
    supplied by vd_funcs. vd_args can be used to provide these funcs with additional
    arguments.
    """
    for f, a in zip(vd_funcs, vd_args):
        try:
            return f(datestring, *a) # see if the function works, return if so
        except ValueError:
            continue # try next
    else:
        return None # no function worked, invalid date string
    
# the functions you want to use to see if they parse the string    
vd_funcs = (dateutil.parser.parse, datetime.strptime, datetime.strptime)
# arguments to these functions, after passing the date string itself.
vd_args = ((None,), ('%m%d%Y',), ('%d%m%Y',))    

running this for the list of example date strings gives

valid=[]
invalid=[]  
for s in ['201222020','20-12-2020','12122020', '53122020']:
    vd = validate(s, vd_funcs, vd_args)
    if vd:
        valid.append(vd)
    else:
        invalid.append(s)
    
valid
[datetime.datetime(2020, 12, 20, 0, 0), datetime.datetime(2020, 12, 12, 0, 0)]

invalid
['201222020', '53122020']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM