Computer Science, asked by sumiit1910, 11 months ago

How do we use Python regular expression to match a date string?

Answers

Answered by pandeysakshi2003
1

Instead of using regex, it is generally better to parse the string as a datetime.datetime object:

In [140]: datetime.datetime.strptime("11/12/98","%m/%d/%y")

Out[140]: datetime.datetime(1998, 11, 12, 0, 0)

In [141]: datetime.datetime.strptime("11/12/98","%d/%m/%y")

Out[141]: datetime.datetime(1998, 12, 11, 0, 0)

You could then access the day, month, and year (and hour, minutes, and seconds) as attributes of the datetime.datetime object:

In [143]: date.year

Out[143]: 1998

In [144]: date.month

Out[144]: 11

In [145]: date.day

Out[145]: 12

To test if a sequence of digits separated by forward-slashes represents a valid date, you could use a try.

please make me brainlist

Similar questions