Search code examples
pythondatetimestrptime

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?


Solution

  • 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