In Python there are multiple DateTime parser's which can parse a date string automatically without proving the datetime format. e.g. DateParser, DateUtils. However, There is no option in any of them where the format in which the date was parsed is returned. What should be done to get the format with which automatic parser's parsed the date as in the example below? e.g parse("2019/05/20") -- > [datetime(2019,5,20,0,0) , "%Y/%m/%d"]
-
What is the question?Bayleef– Bayleef2019-08-31 23:58:59 +00:00Commented Aug 31, 2019 at 23:58
-
How can i get the format with which the date was parsed?user4428032– user44280322019-08-31 23:59:46 +00:00Commented Aug 31, 2019 at 23:59
-
I had the same problem. Eventually I created a list of common datetime formats and parsed string with them in Try-Catch to get the right format. I don't know the use case but you can always ask user to provide the format (of course with with proper help and example)Syed Mohammad Hosseini– Syed Mohammad Hosseini2019-12-14 10:25:02 +00:00Commented Dec 14, 2019 at 10:25
2 Answers
If you want the format string to be able to format datetime objects the same way, I don’t think this is possible, because these parsers (at least dateparser) can parse dates that simply cannot be expressed as a format string.
There is a feature request for it, though. Maybe it can be implemented in some way, or for a subset of all possible inputs.
If you want this for debugging purposes, to understand how a given string could cause a given datetime, I don’t think there is an easy way at the moment either. But if you are getting unexpected results, there are settings you can use to influence different parsing aspects to get the desired results. Date order, input format strings and locales can make quite a difference.
Comments
If you look into the source code of those libraries, you can find out how they are parsing their dates.
For example, DataParser is using a combination of regex and the datetime string formatting directives. Here is the link to their parser: https://github.com/scrapinghub/dateparser/blob/master/dateparser/parser.py
2 Comments
parser.py, and assumed that that is probably where they are parsing their dates... Also, there is a search module, that is also a potential place where they are searching for dates.