Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

python - Adding day and month fields to date field which doesn't contain them

Say we have a list like this:

['1987', '1994-04', '2001-05-03']

We would like to convert these strings into datetime objects with a consistent format, then back into strings, something like this:

['1987-01-01', '1994-04-01', '2001-05-03']

In this case, we have decided if the date doesn't contain a month or a day, we set it to the first of that respective field. Is there a way to achieve this using a datetime or only by string detection?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Read about datetime module to understand the basics of handling dates and date-like strings in Python.

The below approach using try-except is one of the many ways to achieve the desired outcome.:

from datetime import datetime


strings = ['1987', '1994-04', '2001-05-03']

INPUT_FORMATS = ('%Y', '%Y-%m', '%Y-%m-%d')
OUTPUT_FORMAT = '%Y-%m-%d'

output = []
for s in strings:
    dt = None
    for f in INPUT_FORMATS:
        try:
            dt = datetime.strptime(s, f)
            break
        except ValueError:
            pass
        except:
            raise
     
    if not dt:
         raise ValueError("%s doesn't match any of the formats" % s)

    output.append(dt.date().strftime(OUTPUT_FORMAT))

print(output)

Output:

['1987-01-01', '1994-04-01', '2001-05-03']

The above code will work only with date formats listed in formats variable. You can add additional formats to it if you know them beforehand.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...