Python Check if String is Datetime
To check if a string is DateTime in Python, we can use:
Check if String is Datetime using parse()
parse() is a method of the dateutil module used to parse most formats to represent a date or time. Therefore we’ll use parse() to check if the string is a DateTime
In the following example, we’ll check if my_str is DateTime.
- We’ve imported the parse() module
- We’ve defined my_str to check it
- We’ve used try and except to handle the parse() errors
- We’ve checked my_str using parse() with Set fuzzy=False
If you set fuzzy=False, parse() will check whether the string is a date, time, or both. Otherwise, If you set fuzzy=True will check if the string contains a date or time or both.
Finally, if the string is the Datetime, the program returns True. If not, it returns False.
Let’s see another example of a Date:
Now let’s check a Date and Time string.
Now let's try to check a string that contains DateTime:
Oops! It is False. As I said, when you set fuzzy=False, the parser() method will check whether the string is a date, time, or both.
However, to check if the string contains DateTime, we need to set fuzzy=True.
datetime() is a module used to work with date and time. We can use the datetime() to check if a string is a specific date and time format.
The following example will check if my_str is Date with Year-Month-Day format.
%Y-%m-%d: Year-Month-Day format
Let’s check another format:
Here we got False because my_str date format is Year/month/day.
The following example will check for Year-month-day Hours:Minutes format.
Check if String is Date in Python
To check if a string is a date, you can use the Python strptime() function from the datetime module. strptime() takes a string and a date format.
from datetime import datetime string = "06/02/2022" format_ddmmyyyy = "%d/%m/%Y" format_yyyymmdd = "%Y-%m-%d" try: date = datetime.strptime(string, format_ddmmyyyy) print("The string is a date with format " + format_ddmmyyyy) except ValueError: print("The string is not a date with format " + format_ddmmyyyy) try: date = datetime.strptime(string, format_yyyymmdd) print("The string is a date with format " + format_yyyymmdd) except ValueError: print("The string is not a date with format " + format_yyyymmdd) #Output: The string is a date with format %d/%m/%Y The string is not a date with format %Y-%m-%
When working with strings in Python, the ability to check if a string is a date can be very useful.
You can check if a string is a date using the Python strptime() function from the datetime module.
strptime() takes a string and a date format, and tries to create a datetime object. If the string matches the given string format, then the datetime object is created. If not, a ValueError occurs.
You can use a try-except block to try to create a datetime object with strptime() and if it succeeds, then you know the string is a date.
Below is a simple example showing you how to check if a string is a date in your Python code.
from datetime import datetime string = "06/02/2022" format_ddmmyyyy = "%d/%m/%Y" format_yyyymmdd = "%Y-%m-%d" try: date = datetime.strptime(string, format_ddmmyyyy) print("The string is a date with format " + format_ddmmyyyy) except ValueError: print("The string is not a date with format " + format_ddmmyyyy) try: date = datetime.strptime(string, format_yyyymmdd) print("The string is a date with format " + format_yyyymmdd) except ValueError: print("The string is not a date with format " + format_yyyymmdd) #Output: The string is a date with format %d/%m/%Y The string is not a date with format %Y-%m-%
How to Check if String has Specific Date Format in Python
If you want to check if a string is a date, you need to pass strptime() the correct date format.
There are a number of format codes which allow you to create different date and time formats.
You can check if a string is a specific date format by building a date format with the format codes linked above and then use strptime().
For example, if you want to check that a string is a date with format YYYYMMDD, you can use the format “%Y-%m-%d”.
string = "2022-06-02" format_YYYYMMDD = "%Y-%m-%d" try: date = datetime.strptime(string, format_YYYYMMDD) print("The string is a date with format " + format_YYYYMMDD) except ValueError: print("The string is not a date with format " + format_YYYYMMDD) #Output: The string is a date with format %Y-%m-%d
Hopefully this article has been useful for you to learn how to use strptime() to check if a string is a date in Python.
Other Articles You’ll Also Like:
- 1. Using Python to Create List of Prime Numbers
- 2. How to Capitalize the First Letter of Every Word in Python
- 3. How to Remove All Spaces from String in Python
- 4. pandas nsmallest – Find Smallest Values in Series or Dataframe
- 5. How to Draw a Triangle in Python Using turtle Module
- 6. Remove None From List Using Python
- 7. Read Pickle Files with pandas read_pickle Function
- 8. Python getsizeof() Function – Get Size of Object
- 9. math gcd Python – Find Greatest Common Divisor with math.gcd() Function
- 10. Using Python to Sum Odd Numbers in List
About The Programming Expert
The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.
Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.
At the end of the day, we want to be able to just push a button and let the code do it’s magic.
You can read more about us on our about page.
How to check if a date is valid or not in python
In this tutorial, we will check if a date is valid or not using Python. A date is called valid if it actually exists in the calendar.
Our program will ask the user to enter the date at the beginning of the program. It will then check the validity of the date and print out the result on the console.
For example, if the date is ‘01/02/2012’, it will print ‘Input date is valid’ and if the date is ‘31/02/2012’, it will print ‘Input date is not valid.’.
To check the validity of the date, we will use one Python module called ’datetime’. This module doesn’t provide any dedicated method to check if a date is valid or not but we will use this module with a simple trick to find out if a date is valid or not.
Before going into details, let me quickly introduce you to the datetime module :
Python datetime module is one of the most useful modules to work with simple and complex date-time values. We can import this module to a Python program by using the import datetime statement at the beginning of a program.
This module provides a lot of different methods to work with date-time. For example, we can use this module to print the current time, add days to the current time, add hours to the current time, add minutes to the current time etc.
’aware’ objects can hold additional information with the date time value like daylight saving information etc. These objects are useful if we are dealing with data from different timezones.
The smallest year supported by the ’datetime’ module is stored in the MINYEAR variable and the maximum supported year is stored in the MAXYEAR variable. The value of MINYEAR is 1 and MAXYEAR is 9999.
As I have explained above, it doesn’t provide any method to check the validity of a date. We will use its constructor to create one ’datetime’ object using the user-provided string. If the constructor fails, it will throw one error and we can say that the input string is not representing a valid date-time.
- Get the input from the user
- Input should be in the form of dd/mm/yy
- Extract the inputs in different variables. e.g. if the user input is 02/04/99, we will extract the numbers 02, 04, and 99 and store them in three different variables.
- Use the constructor of ‘datetime’ module to check if the date is valid or not.
- Print out the result.
import datetime inputDate = input("Enter the date in format 'dd/mm/yy' : ") day, month, year = inputDate.split('/') isValidDate = True try: datetime.datetime(int(year), int(month), int(day)) except ValueError: isValidDate = False if(isValidDate): print("Input date is valid ..") else: print("Input date is not valid..")
- The above example is compatible with python3. First of all, we are getting the date from the user as ‘dd/mm/yy’.
- By using the split method, we are extracting the day, month and year values from the string.
- The isValidDate flag is used to determine if the user-provided date is valid or not. If its value is True , it is a valid date, else it is not.
- datetime.datetime() is the constructor we are using to create one ‘datetime’ variable by using the user provided values. If it fails, it will throw one ’ValueError’. We are setting the value of ’isValidDate’ flag to ’False’ here.
- Finally, print out the result to the user based on the value of ’isValidDate’ flag.
Method 2: By using datetime.strptime() method:
If we use the datetime.datetime constructor, we have to split the date-time string to get the year, month and day values. Instead of splitting the string, we can also use the datetime.strptime() method. We can define the format string and it will use that format string to parse the given date string.
It raises ValueError if the string can’t be parsed as defined by the format. Similar to the above example, we can use a try-catch block to check if the given string is a valid date-time string or not.
Let’s use this method to check if a date is valid or not:
from datetime import datetime inputDate = input("Enter the date in format 'dd/mm/yy' : ") date_format = "%d/%m/%y" isValidDate = True try: datetime.strptime(inputDate, date_format) except ValueError: isValidDate = False if(isValidDate): print("Input date is valid ..") else: print("Input date is not valid..")
This approach is better than the previous one as we need to pass the format instead of splitting the string to find the values.
in format 'dd/mm/yy' : 12/12/22 Input date is valid ..
Method 3: By using python-dateutil:
With this method, we will use the python-dateutil module to check if a date-time string is valid or not. This module provides extension functions to the datetime module. You can use the below command to add it to your project:
This module provides a parser function that can parse most of the known date-time formats. Unlike the above example, we don’t need to pass the format string to this function.
It can throw a ParseError for an invalid string. We can use a try-catch block to check if the date string is valid or not.
from dateutil import parser inputDate = input("Enter the date in any valid format: ") isValidDate = True try: print(parser.parse(inputDate)) except ValueError: isValidDate = False if(isValidDate): print("Input date is valid ..") else: print("Input date is not valid..")
in any valid format: 31-03-22 2022-03-31 00:00:00 Input date is valid .. Enter the date in any valid format: 03-31-22 2022-03-31 00:00:00 Input date is valid ..
We learned three different ways to check if a date-time string is valid or not. The datetime.strptime method is better if you want to test the string with a predefined format string. If we don’t know the format and we just want to know if a string represents a valid date-time or not, we can use the python-dateutil module.