How to validate a specific Date and Time format using Python

非 Y 不嫁゛ 提交于 2019-12-05 09:15:15

Yes, you can use datetime.strptime():

from datetime import datetime


def validate_date(d):
    try:
        datetime.strptime(d, '%m/%d/%Y %I:%M %p')
        return True
    except ValueError:
        return False


print validate_date('2/26/2009 3:00 PM')  # prints True
print validate_date('2/26/2009 13:00 PM')  # prints false
print validate_date('2/26/2009')  # prints False
print validate_date("Should I use regex for validating dates in Python?")  # prints False
Srinivas Reddy Thatiparthy

This is how you do it:

    from datetime import datetime

    def validate(datetime_string):
        try:
            return datetime.strptime(datetime_string,"%m/%d/%Y %I:%M %p")
        except ValueError:
            return False
import datetime
parsed = datetime.datetime.strptime("2/26/2009 3:00 PM", r'%m/%d/%Y %H:%M %p')
iso_formatted = parsed.isoformat()
print(iso_formatted)

You could use locale module combined with time.strptime() to ensure the date/time is in the proper order (month, day, year, etc). Or, you could do simple regex...

pattern = re.compile(r'\d{1,2}/\d{1,2}/\d{4} \d{1,2}:\d{2} (AM|PM)') ...I am not a regex pro lol, there's probably a better pattern.

You can also use the datetime module and create a new datetime object with the locale constant and have it convert the numbers to their proper type (day, month, year).

Good luck!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!