0

I am trying to strip off the time stamp from a string for e.g. '9/10/20151:03 PM' Note that there is intentionally no space between the date and time.
Here's the code:

datetime.strptime(date, "%m/%d/%Y%I:%M %p")

However, I might get bad strings like '9/10/2015 1:03 PM' ( with a space between date and time). I am contemplating to grep the incoming string for a pattern and decide which pattern to use in my strptime method.

My question is that is there a better way to do this? I looked at documentation of strptime method and it doesn't support multiple patterns. The only other way I can think of is following ( but it doesn't support more than two patterns )

try:
    time = datetime.strptime(date, "%m/%d/%Y%I:%M %p")
except Exception as e:
    time = datetime.strptime(date, "%m/%d/%Y %I:%M %p")

CONSTRAINTS: 1. Cannot depend on a library except datetime since I am going to push it to production as a bug fix.

2 Answers 2

1
$ pip install python-dateutil


...
>>> from dateutil.parser import parse
>>> print parse(my_date_string)

the dateutil library does a great job of converting any string to a date and its almost always right ...

without using it you could certainly do something like

date = date_string[:10] # mm/dd/YYYY
rest = strip(date_string[10:]
timestamp = date+" "+rest
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Joran. I am going to be pushing the code to production hence not looking for dependency on a library. I will mention that in the question.
in that case you know the date is always the first 10 characters
nah that won't work. '9/10/20151:03 PM' results into '9/10/20151 :03 PM' [ wrong] '12/10/20151:03 PM' results into '12/10/2015 1:03 PM'[correct]
0

Something like:

from datetime import datetime

# more patterns as you need.
PATTERNS = ["%m/%d/%Y%I:%M %p", "%m/%d/%Y %I:%M %p"]

def GetDate(dateStr):
   '''
      Attempt to parse a string and create a datetime.datetime object
      using a list of potential date format patterns. Returns None if 
      it's unable to make sense of the string as a date. 

      >>> GetDate("3/1/20154:15 PM")
      datetime.datetime(2015, 3, 1, 16, 15)
      >>> GetDate("3/1/2015 4:15 PM")
      datetime.datetime(2015, 3, 1, 16, 15)
      >>> GetDate("not a date")
      >>>

   '''
   for pattern in PATTERNS:
      try:
         return datetime.strptime(dateStr, pattern)
      except ValueError:
         # loop to the next pattern
         continue
   return None


if __name__ == "__main__":
   import doctest
   doctest.testmod()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.