jacobcan118
jacobcan118

Reputation: 9057

how to verified the string as correct date format

can I know the best way for me to verified the string is in the following formate. I am not sure how i should verified the house and (am or pm)

datestring = 'Feb 22 2017, 1:27:42pm'
print(datetime.strptime('Feb 22 2017, 1:27:42', '%b %d %Y, %H:%m:%S'))

Upvotes: 1

Views: 127

Answers (2)

Некто
Некто

Reputation: 1820

Use regex to see if an entry is in your format. It will return either a SRE_Match object or nothing, so call bool on the regex to return True/False

>>> datestring = 'Feb 22 2017, 1:27:42pm'
>>> bool(re.match(r'([A-Z][a-z]{2} \d{2} \d{4}, \d:\d{2}:\d{2}[am,pm])', datestring))
    True

Upvotes: 0

Mad Physicist
Mad Physicist

Reputation: 114350

Your main issue is actually that %m should be %M. Lowercase m is the month, not the minute. %p will parse 'am' and 'pm'. You may also want to change %H to %I since the presence of am/pm implies a 12 hour clock rather than 24:

datestring = 'Feb 22 2017, 1:27:42pm'
datetime.strptime(datestring, '%b %d %Y, %I:%M:%S%p')

Results in a datetime object that can be represented as 2017-02-22 13:27:42 with my locale/platform defaults.

Upvotes: 1

Related Questions