Python является ли значение датой

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.

Читайте также:  Call non static function in static function php

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.

  • 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 do date validation in Python?

You can use many other directives to parse the date. Following are the directives supported by strptime()’s format string.

Directive Meaning
%a Locale’s abbreviated weekday name.
%A Locale’s full weekday name.
%b Locale’s abbreviated month name.
%B Locale’s full month name.
%c Locale’s appropriate date and time representation.
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number [00,23].
%I Hour (12-hour clock) as a decimal number [01,12].
%j Day of the year as a decimal number [001,366].
%m Month as a decimal number [01,12].
%M Minute as a decimal number [00,59].
%p Locale’s equivalent of either AM or PM.
%S Second as a decimal number [00,61].
%U Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0.
%w Weekday as a decimal number [0(Sunday),6].
%W Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0.
%x Locale’s appropriate date representation.
%X Locale’s appropriate time representation.
%y Year without century as a decimal number [00,99].
%Y Year with century as a decimal number.
%Z Time zone name (no characters if no time zone exists).
%% A literal «%» character

Method 2: Using dateutil.parser.parse() function

In this method, we use a separate inbuilt function, dateutil.parser, to check for validated format. This does not require the format to validate a date.

Algorithm (Steps)

The parser module can parse datetime strings in a number of different formats. To parse dates and times in Python, there is no better package than dateutil. The tz module includes everything needed to look for timezones. When these modules are used together, it is relatively simple to convert strings into timezone−aware datetime objects.
  • Enter the date as a string and create a variable to store it.
  • Print the given input date.
  • Use the try−except blocks for handling the exceptions. Inside the try block, parse the given date string using the parse() function. Here it prints true if the given date is correct.
  • If the date is not correct/invalid then the except block code will be executed. Here If there is a parsing error for the given date then it will throw ValueError so the except block handles the ValueError and we print some text to say the given date is not validated.

Example

The following program returns whether the given date is valid or not using the parse() function −

# importing parser from dateutil module from dateutil import parser # input date date_string = '23-41-2021' # printing the input date print("Input Date:", date_string) # using try-except blocks for handling the exceptions try: # parsing the date string using parse() function # It returns true if the date is correctly formatted else it will go to except block print(bool(parser.parse(date_string))) # If the date validation goes wrong except ValueError: # printing the appropriate text if ValueError occurs print("Incorrect data format")

Output

On executing, the above program will generate the following output −

Input Date: 23-41-2021 Incorrect data format

Conclusion

We learned how to validate a given date using two different methods in this article. We also learned about the other directives that strptime() function supports.

Источник

Как проверить формат строки даты в Python?

У меня есть метод python, который принимает ввод даты как строку. Как добавить подтверждение, чтобы строка даты передавалась методу в ffg. Формат:

Может быть, больше Pythonic (просить прощения, а не разрешения) вообще не проверять и перехватывать любые возникающие исключения.

5 ответов

>>> import datetime >>> def validate(date_text): try: datetime.datetime.strptime(date_text, '%Y-%m-%d') except ValueError: raise ValueError("Incorrect data format, should be YYYY-MM-DD") >>> validate('2003-12-23') >>> validate('2003-12-32') Traceback (most recent call last): File "", line 1, in validate('2003-12-32') File "", line 5, in validate raise ValueError("Incorrect data format, should be YYYY-MM-DD") ValueError: Incorrect data format, should be YYYY-MM-DD 

Есть ли способ сделать это без попытки / кроме? Python имеет тенденцию к значительному замедлению при возникновении и обнаружении исключения.

@chiffa Вы можете сопоставить регулярное выражение формата даты, но это не рекомендуется, поскольку оно менее надежно и исключения более понятны. Вы уверены, что проверка даты является вашим узким местом?

Не совсем, поэтому в конце я просто добавлю функцию throw-кроме в функцию. Я просто удивлен, что в библиотеке datetime нет функции проверки, возвращающей bool, которая бы вызывала исключение.

@chiffa Возможно, они не включили функцию bool, возвращающую функцию проверки, она может существовать во внешних библиотеках.

Я знаю, что это было больше года, но я разбирал некоторые журналы и случайно вычеркивал строки, которые не начинались с даты. Я только что проверил предложенный метод против проверки временной последовательности для «setswith (<текущий год>)». ~ 590к строк бревен. Использование парсера dateutil и его исключений: 129 сек. Использование тупого как ад «начинается с»: 3 сек. Теперь я знаю, что это не работает для всех, но если метод, который работает в большинстве случаев, на 2 порядка быстрее, то на 2 порядка быстрее. У меня есть примерно в 2000 раз больше логов для проработки моего сценария, угадайте, что я буду использовать?

Для тех, кто хочет заполнить нулями даты, это решение не будет работать, поскольку strptime не является строгим в отношении заполнения нулями. Реализуйте собственное регулярное выражение или проверьте длину результирующей строки после удаления пробелов, а затем воспользуйтесь этим решением.

@MiaoLiu В вашем случае вы нашли метод, который является самым быстрым в сырой скорости, вы сделали правильную вещь. это более общее решение для другой проблемы

Да, согласен с @Suparshva Например, эта строка будет считаться правильной датой без ValueError: «2018-10-1»

Библиотека Python dateutil предназначена для этого (и более). Он автоматически преобразует это в объект datetime для вас и поднимет ValueError , если он не может.

>>> from dateutil.parser import parse >>> parse("2003-09-25") datetime.datetime(2003, 9, 25, 0, 0) 

Возникает ValueError , если дата не отформатирована правильно:

>>> parse("2003-09-251") Traceback (most recent call last): File "", line 1, in File "/Users/jacinda/envs/dod-backend-dev/lib/python2.7/site-packages/dateutil/parser.py", line 720, in parse return DEFAULTPARSER.parse(timestr, **kwargs) File "/Users/jacinda/envs/dod-backend-dev/lib/python2.7/site-packages/dateutil/parser.py", line 317, in parse ret = default.replace(**repl) ValueError: day is out of range for month 

dateutil также чрезвычайно полезен, если вы начнете в дальнейшем анализировать другие форматы, так как он может обрабатывать наиболее известные форматы разумно и позволяет вам изменять свои спецификации: dateutil примеры анализа.

Он также обрабатывает часовые пояса, если вам это нужно.

Обновление на основе комментариев: parse также принимает аргумент ключевого слова dayfirst , который контролирует, будет ли день или месяц ожидаться первым, если дата неоднозначна. По умолчанию это значение False. Например.

>>> parse('11/12/2001') >>> datetime.datetime(2001, 11, 12, 0, 0) # Nov 12 >>> parse('11/12/2001', dayfirst=True) >>> datetime.datetime(2001, 12, 11, 0, 0) # Dec 11 

он может принять слишком много, например, parse(’13/12/2001′) равен «13 декабря», но parse(’11/12/2001′) равен «12 ноября» (первый результат предполагает «11 декабря» здесь) ,

parse фактически принимает аргумент dayfirst ключевого слова, который позволяет вам контролировать это. parse(’11/12/2001′, dayfirst=True) вернет «11 декабря» По умолчанию dayfirst=False является dayfirst=False

вы упускаете момент, когда datetutil.parser.parse() принимает слишком много форматов времени (вы можете найти другие примеры с неоднозначным вводом). Если вы хотите проверить, что ваш ввод в формате ГГГГ-ММ-ДД, то функция parse() — это неправильный инструмент.

Это абсолютно верный момент — если вы действительно хотите ограничиться только этим конкретным форматом, это не делает этого, и принятый ответ уже делает большую работу, выполняя правильные действия в этом случае. Я думаю, что когда я писал ответ, я больше думал о том, как проверить, была ли это правильная дата, в отличие от конкретного формата, который запрашивал автор, — когда люди сталкиваются с этим вопросом, они часто находясь в поиске.

Источник

Оцените статью