2

How do I get the date format for the given date input in python? Note: The input is given by the user which is not predefined format .They may give any kind of input format .. The below example is working for dd-mm-yyyy format .But this is not in my case.Date format is not predefined. datetime.datetime.strptime('24052010', "%d%m%Y").date()

Expected :

Input 1: 21–02–2019 ,Output: DD-MM-YYYY . Input 2: 02/21/2019 ,Output : MM/DD/YYYY

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40

3 Answers3

1

I think such function cannot be done because some dates (for example 01/01/2019) cannot be interpreted in one way. This can be both MM/DD/YYYY and DD/MM/YYYY. So you can only check if the date is in such format or not (you can use the answers to this question: How do I validate a date string format in python?).

J Kluseczka
  • 1,150
  • 9
  • 14
0

You can use the module dateutil. It has a robust parser that will try to make sense of any date.

>>> from dateutil import parser
>>> parser.parse("21-02-2019")
datetime.datetime(2019, 2, 21, 0, 0)
>>> parser.parse("02/21/2019")
datetime.datetime(2019, 2, 21, 0, 0)

This isn't exactly what you wanted: you get the date not the format. But if you have the date, do you really need the format?

To meet J Kluseczka's point about some dates being ambiguous (like "01/10/2019") you can specify your assumption:

>>> parser.parse("01/10/2019")
datetime.datetime(2019, 1, 10, 0, 0)
>>> parser.parse("01/10/2019",dayfirst=True)
datetime.datetime(2019, 10, 1, 0, 0)

dateutil isn't part of the standard library but it is well worth the trouble of downloading.

BoarGules
  • 16,440
  • 2
  • 27
  • 44
  • I have a pattern which is collection of date formats,if my input matched with any of the format in my pattern ,then i'll process further with the matched dates. That's why i'm asking the date format !!!! – Gomathimeena Subburayan Feb 21 '19 at 13:00
  • If that is what you want to do, then call `datetime.datetime.strptime()` on the first 3 or 4 strings in the file with all of the formats in your collection, accept the first result that doesn't throw an exception, and use that format to process the rest of the file. Though, having done exactly that myself, I suspect that you will discover that the dates in any one input file are not as consistently in one format as you clearly expect they will be. – BoarGules Feb 21 '19 at 13:07
  • Let me try and inform you BoarGules ! – Gomathimeena Subburayan Feb 21 '19 at 13:15
-1

pandas to_datetime function has this functionality and is vectorized with numpy so its fast over arrays.

ex:

>>> from pandas import to_datetime
>>> to_datetime("2023-07-07")
datetime.datetime(2023,7,7,0,0)
starball
  • 20,030
  • 7
  • 43
  • 238