2

I want to create a function or a loop with the conditional: if this string follows this format is a date, so return True, otherwise return False.

I already tried it with this code, but when I run is_date(string) it returns False, and it should return True.

string = '20090903'
def is_date(string):
    if string.format == "%YYYY%mm%dd":
        return True
    else:
        return False
is_date(string)
David Mora
  • 101
  • 1
  • 8
  • Take a look at this other [issue](https://stackoverflow.com/questions/25341945/check-if-string-has-date-any-format). – Nakor Jul 11 '19 at 02:22

4 Answers4

2

Try checking if the length is eight and the string only contains digits:

string = '20090903'
def is_date(string):
    return len(string) == 8 and string.isdigit()
print(is_date(string))

A more precise solution:

string = '20090903'
from dateutil.parser import parse 
def is_date(string):
    try:
        parse(string)
        return True
    except:
        return False
print(is_date(string))

This solution will give False on 00000000, but not the first solution:

Both Output:

True
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
2

Since you tag pandas

string = '20090903'
from pandas.core.tools.datetimes import _guess_datetime_format_for_array

def is_date(string):
    return _guess_datetime_format_for_array(np.array([string ])) == '%Y%m%d'

is_date(string)

More test

is_date('20190101')
Out[77]: True
is_date('00000000')
Out[78]: False
BENY
  • 317,841
  • 20
  • 164
  • 234
2

you dont need pandas to do it:)

from datetime import datetime
def test(your_text):
    try:
        datetime.strptime(your_text, '%Y%m%d')
        print('valid format')
        return True
    except ValueError:
        return False

if __name__=='__main__':
    test('20090903')
1

Here is a function that will only return true if the string in that specific format: enter image description here