Home > OS >  Recognize date format and convert it
Recognize date format and convert it

Time:01-08

Is there a way where to guess date format of a string and convert other dates to the same format as the given string (e.g. YYYYMMDD)?

For example:

# Recognize the format as YYYYMMDD
date1 = '20221111'

# Recognize the format as YYYY-MM-DD and converts to YYYYMMDD
date2 = '2022-11-12'

CodePudding user response:

You can use dateutil.parser.parse(), which can parse dates dynamically.

For example:

from dateutil import parser

date1 = '20221113'
date2 = '2022-11-13'

print(parser.parse(date1).strftime('%d-%m-%Y'))
print(parser.parse(date2).strftime('%Y%m%d'))

#13-11-2022
#20221113

CodePudding user response:

I don't quite understand what you mean by "guessing the date format" what you mean is changing the default way Python works with dates? Because that is difficult if not impossible. Secondly if you want to format that text why not use datetime.

from datetime import datetime
datetime.strptime("20221112", '%Y%m%d') # datetime.datetime(2022, 12, 11, 0, 0)
# Or you can also try
datetime.strptime("20221211", '%Y%d%m') # datetime.datetime(2022, 11, 12, 0, 0)

if you are bothered by using datetime.strptime you can use it in a function

def format_time(time_str, format='%Y%m%d'):
  return datetime.strptime(time_str, format)
print(format_time("20231011")) # 2023-10-11 00:00:00

As a resource I leave you this to help you with formats Python Strptime

Of course, if you don't know how the sample data comes, you will have to interpret it by default because it is impossible to know how to interpret it. I would personally use YYYYMMDD

CodePudding user response:

If you can't ensure that all data follows one convention like ISO. Then the alternative solution would be using some wrapper function to parse the given string to date using regexes / multiple try except blocks with datetime.strptime(pattern, string).

  • Related