7

I am writing a program to validate portions of an XML file. One of the points I would like to validate is a Date Time format. I've read up on the forum about using time.strptime() but the examples weren't quite working for me and were a little over my expertise. Anyone have any ideas how I could validate the following. This is the format the date and time must be in.

2/26/2009 3:00 PM

I am sure there is something built-in and very easy but I can't find. Many thanks if you've run by this before and have suggestions.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
user2643864
  • 641
  • 3
  • 11
  • 24
  • What do you mean validate the datetime? Do you want to ensure it is properly formatted, an actual date that makes sense (i.e. not 13/45/20000), fits some other criteria? What do you want to do with the datetime data after "validation"? – wflynny Aug 30 '13 at 18:33
  • My first goal was to make sure it was properly formatted. – user2643864 Aug 30 '13 at 19:30

4 Answers4

23

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
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Great answer. Following typical [EAFP](http://docs.python.org/2/glossary.html#term-eafp) style, the simplest and most robust way to test whether you can FOO a BAR is usually to just FOO it and see if it works… – abarnert Aug 30 '13 at 18:41
  • @abarnert thank you, asking for forgiveness is definitely easier! – alecxe Aug 30 '13 at 18:46
3

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
Daniel Mann
  • 57,011
  • 13
  • 100
  • 120
1
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)
m.kocikowski
  • 5,422
  • 2
  • 23
  • 9
0

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!

blakev
  • 4,154
  • 2
  • 32
  • 52