How to check date and time format using Python

I am writing a program to check parts of an XML file. One of the things I would like to confirm is the date format. I read on the forum about using time.strptime() , but the examples didn’t quite work for me and were a little more than my experience. Does anyone have any ideas how I can confirm the following. This is the format in which the date and time must be.

 2/26/2009 3:00 PM 

I am sure there is something built-in and very simple, but I can not find. Thank you very much if you ran this earlier and received suggestions.

+4
source share
4 answers

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 
+18
source

Here's 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 
+3
source
 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) 
+1
source

You can use the local module in conjunction with time.strptime() to ensure that the date / time is in the correct order (month, day, year, etc.). Or you can do a 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, perhaps the best sample.

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

Good luck

0
source

Source: https://habr.com/ru/post/1499849/


All Articles