Nikola Stoyanov
Nikola Stoyanov

Reputation: 59

How can you convert a string with varying length to datetime

I have a list that has strings with Y-M-D (eg. 2010-01-14) format, but some don't have the month and/or the day. I've tried doing it based on the length but it became long and messy. Is there an easy way to accomplish this?

Upvotes: 0

Views: 280

Answers (1)

FObersteiner
FObersteiner

Reputation: 25594

does this satisfy your needs: dateutil's parser with a default date, Ex:

from datetime import datetime
from dateutil import parser

for s in '2021', '2021-01', '2021-02-03':
    print(parser.parse(s, default=datetime(2021,1,1)))
    
2021-01-01 00:00:00
2021-01-01 00:00:00
2021-02-03 00:00:00

Upvotes: 1

Related Questions