I would like to check if the date exists from the method of entering the 4-digit date specified here.
For example, August 23rd is like 0823, and this is a date that actually exists, but if it is an impossible date like 9999, I would like to issue an error.
I would appreciate it if you could tell me how to check if a 4-digit number exists from the 4-digit and numeric check.
time=input("Please enter a date:")
iflen(time) == 4:
if time.isdigit() == True:
print("Normal")
else:
print("Not a number")
else:
print("The number of digits is different"")
If you google "python date validation", for example, the following pages will be hit.
How do I validate a date string format in python?- Stack Overflow
Refer to one of the answers, which shows you how to use the datetime module:
from datetime import datetime
datetime.strptime(date_string, "%Y-%m-%d")
If an incorrect date is specified, a ValueError
will occur, so you may want to write an exception using try
and expect
.
To apply to the example of this question, the formatting part of the date is as follows:
datetime.strptime(date_string, "%m%d")
The following is how to use the Pandas module to_datetime()
.
import pandas as pd
default_date_string(date_str):
return len(date_str) == 4 and \
pd.to_datetime(f'2000 {date_str}, format='%Y%m%d', errors='coerce')is not pd.NaT
if__name__=='__main__':
testing=['0801', '0229', '9999', 'abcd' ]
Fort in testing:
print(validate_date_string(t))
It's an irregular code, but you can also check the validity of the regular expression.
In the code below, passing a string to the is_date
function returns True if it is a 4-digit month-day string (including leap year "0229").
import re
defis_date(s:str)->bool:
pattern=re.compile("(01|03|05|07|08|10|12)(0[1-9]|[12][0-9]|3[01]$|"# Months through 31st\
"(04|06|09|11) (0[1-9]|[12][0-9]|30)$|"#Month through 30th\
"(02(0[1-9]|[12][0-9]))$")#29th month
return pattern.match(s)!=None
# normal data
assert is_date("0101")
assert is_date("0229")
assert is_date("0430")
assert is_date("1231")
# anomaly data
assert is_date("0000") == False
assert is_date("0132") == False
assert is_date("0230") == False
assert is_date("1301") == False
assert is_date("9999") == False
assert is_date("101") == False
assert is_date("01011") == False
assert is_date("OIOI") == False
References
Read the regular expression to check the validity of the yyyymmdd format date string
That's what I think.
print("Normal")
with the following actions:
© 2024 OneMinuteCode. All rights reserved.