Reputation: 9057
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
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
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