Python является ли строка датой

В python, как проверить, действительна ли дата?

Ввод от пользователя затем отправляется на сервер cherrypy. Мне интересно, есть ли способ проверить, является ли дата, введенная пользователем, действительной датой? Очевидно, я мог бы написать множество операторов if, но есть ли встроенная функция, которая может это проверить? Спасибо

Ответы (10)

import datetime datetime.datetime(year=year,month=month,day=day,hour=hour) 

это устранит такие вещи, как месяцы> 12, часы> 23, несуществующие високосные дни (месяц = ​​2 имеет максимум 28 в невисокосные годы, 29 в противном случае, другие месяцы имеют максимум 30 или 31 день) (выдает исключение ValueError при ошибке) Также вы можете попытаться сравнить его с некоторыми верхними/нижними границами здравомыслия. бывший.:

datetime.date(year=2000, month=1,day=1) < datetime.datetime(year=year,month=month,day=day,hour=hour)  

Соответствующие верхняя и нижняя границы здравомыслия зависят от ваших потребностей. редактировать: помните, что это не обрабатывает определенные даты и время, которые могут быть недействительны для вашего приложения (минимальный день рождения, праздники, нерабочие часы и т. д.)

Вы можете попробовать использовать дату и время и обработать исключения, чтобы определить действительную/недействительную дату: Пример: http://codepad.org/XRSYeIJJ

import datetime correctDate = None try: newDate = datetime.datetime(2008,11,42) correctDate = True except ValueError: correctDate = False print(str(correctDate)) 

Вопрос предполагает, что решение без библиотек включает в себя «множество операторов if», но это не так:

def is_valid_date(year, month, day): day_count_for_month = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if year%4==0 and (year%100 != 0 or year%400==0): day_count_for_month[2] = 29 return (1  
>>> from datetime import datetime >>> print datetime(2008,12,2) 2008-12-02 00:00:00 >>> print datetime(2008,13,2) Traceback (most recent call last): File "", line 1, in print datetime(2008,13,2) ValueError: month must be in 1..12 

Но разве это не даст мне сообщение об ошибке? и вызвать все своего рода крах? Я надеялся, что есть функция, которая, например, возвращает 1, если это действительная дата, и возвращает 0, если она недействительна. Затем я могу предложить пользователю повторно ввести дату на веб-странице. - person davidx1; 03.04.2012

Или вы могли бы try. except и поймать ошибку. Затем вы можете делать то, что хотите, молча передавать ошибку, если хотите. - person jamylak; 03.04.2012

import time def is_date_valid(year, month, day): this_date = '%d/%d/%d' % (month, day, year) try: time.strptime(this_date, '%m/%d/%Y') except ValueError: return False else: return True

Вы можете попробовать использовать дату и время и обработать исключения, чтобы определить действительную/недействительную дату:

import datetime def check_date(year, month, day): correctDate = None try: newDate = datetime.datetime(year, month, day) correctDate = True except ValueError: correctDate = False return correctDate #handles obvious problems print(str(check_date(2008,11,42))) #handles leap days print(str(check_date(2016,2,29))) print(str(check_date(2017,2,29))) #handles also standard month length print(str(check_date(2016,3,31))) print(str(check_date(2016,4,31))) 
False True False True False 

Итак, вот мое хакерское решение для исправления неверных дат. Это предполагает, что пользователь отправляет данные из общей HTML-формы, которая предоставляет дни 1-31 в качестве параметров. Основная проблема заключается в том, что пользователи указывают день, которого нет в этом месяце (например, 31 сентября).

def sane_date(year, month, day): # Calculate the last date of the given month nextmonth = datetime.date(year, month, 1) + datetime.timedelta(days=35) lastday = nextmonth.replace(day=1) - datetime.timedelta(days=1) return datetime.date(year, month, min(day, lastday.day)) class tests(unittest.TestCase): def test_sane_date(self): """ Test our sane_date() method""" self.assertEquals(sane_date(2000,9,31), datetime.date(2000,9,30)) self.assertEquals(sane_date(2000,2,31), datetime.date(2000,2,29)) self.assertEquals(sane_date(2000,1,15), datetime.date(2000,1,15)) 
from dateutil.parser import parse def is_valid_date(date): if date: try: parse(date) return True except: return False return False 

Основываясь на ответе @codehia, следующее позволяет также проверить формат даты и разбить строку на год, месяц, день - все вышеперечисленное предполагает, что уже есть год, месяц, день.

from dateutil.parser import parse import string p=print space_punct_dict = dict((ord(punct), ' ') for punct in string.punctuation) def is_valid_date_p(date): if date: try: date = date.translate(space_punct_dict) new_date = str(parse(date))[:10] year = new_date[:4] month = new_date[5:7] day = new_date[8:] p(year, month, day) return True, year, month, day except: p('invalid:', date) return False return False year, month, day = 2021, 6, 1 is_valid_date_p(f'//') is_valid_date_p(f'..') is_valid_date_p(f',,') is_valid_date_p(f'//') is_valid_date_p(f'--') is_valid_date_p(f'  ') p() is_valid_date_p('12/1/20') is_valid_date_p('12/31/20') p() is_valid_date_p('31/12/20') is_valid_date_p('30/6/2020') is_valid_date_p('2020/30/6') 

выход: 2021 06 01 2021 06 01 2021 06 01 2021 06 01 2021 06 01 2021 06 01 2020 12 01 2020 12 31 2020 12 31 2020 06 30 недействительно: 2020 30 6

Хотя это может ответить на вопрос авторов, в нем отсутствуют поясняющие слова и ссылки на документацию. Необработанные фрагменты кода не очень полезны без фраз вокруг них. Вы также можете найти очень полезным как написать хороший ответ. Пожалуйста, отредактируйте свой ответ. - person hellow; 14.09.2018

Источник

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.

  • 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.

Источник

Читайте также:  Php backslash before function
Оцените статью